码迷,mamicode.com
首页 > 编程语言 > 详细

java反射机制——字符串拼接方法名调用方法

时间:2019-11-06 13:39:54      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:targe   test   col   hid   cat   eve   ant   反射机制   turn   

技术图片
 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

 

java反射机制——字符串拼接方法名调用方法

标签:targe   test   col   hid   cat   eve   ant   反射机制   turn   

原文地址:https://www.cnblogs.com/jiaye77/p/11804269.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!