java反射機制——字符串拼接方法名調用方法


 1 public class Person {
 2     public String getPerson1(String i){
 3         return "Person1--"+i;
 4         
 5     }
 6     public String getPerson2(String i){
 7         return "Person2--"+i;
 8         
 9     }
10     public String getPerson3(String i){
11         return "Person3--"+i;
12         
13     }
14 }
View Code
 1 @Test
 2     public void test7() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException{
 3         
 4         Class<?> Person = Class.forName("com.Person");
 5         Object newInstance = Person.newInstance();
 6         for (int i = 1; i < 4; i++) {
 7             Method method = Person.getMethod("getPerson"+i, String.class);
 8             String str2= (String) method.invoke(newInstance, new Object[]{i+""});
 9             System.out.println(str2);
10         }
11     }
View Code
1 Person1--1
2 Person2--2
3 Person3--3

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM