标题:不改变源代码的前提下,创建任意对象,执行任意方法,使用配置文件
不改变源代码的前提下,创建任意对象,执行任意方法
思路同上,只是多了个配置文件的加载,读取
/**
* 使用配置文件完成
* 小测试,不改变源代码的前提下,创建任意对象,执行任意方法,
*
* java.lang.NoSuchMethodException: crazyjava.reflect.Person.setName([Ljava.lang.Object;
* 说明方法写错了,或者形参传错了
* @author dell
*
*/
public class TestDemo032 {
public static void test(String path,String methodName,Class<?>[] parameterTypes,Object...params) throws Exception {
Class<?> clazz = Class.forName(path);
//创建对象
Object obj=clazz.getDeclaredConstructor().newInstance();//这就是反射为什么要无参构造器的原因,让每个类都有无参构造器比有参构造器更容易做到
//调用任何方法
Method method=clazz.getDeclaredMethod(methodName,parameterTypes);//clazz.getMethod(String name, Class<?>... parameterTypes)
method.setAccessible(true);
method.invoke(obj,params);
method=clazz.getMethod("getName");
System.out.println(method.invoke(obj));
}
public static void main(String[] args) throws Exception {
//方式一
//创建Properties类的对象
Properties info=new Properties();
//加载配置文件
info.load(new FileInputStream("E:/eclipse/crazy/src/reflectProperties.properties"));
//读取配置文件
String path = info.getProperty("path");
String methodName = info.getProperty("methodName");
//方式二
// //1.加载配置文件
// //1.1创建Properties类的对象
// Properties info=new Properties();
// //1.2加载配置文件--》集合
// //1.2.1获取class目录下的配置文件
// ClassLoader classLoader = TestDemo032.class.getClassLoader();
// InputStream is = classLoader.getResourceAsStream("reflectProperties.properties");
// info.load(is);
// //读取配置文件
// String path = info.getProperty("path");
// String methodName = info.getProperty("methodName");
TestDemo032.test(path,methodName,new Class<?>[] {String.class,String.class,int.class,double.class},"女","hhh",666,66.6);
}
}