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