1.反射
案例:
需求:写一个“框架”,不能改变该类的任何代码的前提下,可以帮我们创建任意类的对象,并且执行其中任意方法
实现:
1.配置文件
2.反射
步骤:
1.将需要创建的对象的全类名和需要执行的方法定义在配置文件中
2.在程序中加载读取配置文件
3.使用反射技术来加载类文件进内存
4.创建对象
5.执行方法
代码:
结构:
在src下创建File(配置文件),命名pro.properties
文件内容:
className =cn.itcast.domain.Student
methodName= sleep
Student中有sleep方法:
public classStudent {public voidsleep() {
System.out.println("sleep...");
}
}
Person中有eat方法:
public classPerson {public voideat() {
System.out.println("eat...");
}public voideat(String food) {
System.out.println("eat..."+food);
}
}
ReflectTest:
/*** 框架类*/
public classReflectTest {public static void main(String[] args) throwsException {
/*前提:不能改变该类的任何代码,可以创建任意类的对象,可以执行任意方法*/
//1.加载配置文件//1.1创建properties对象
Properties pro = newProperties();//1.2加载配置文件,转换为一个集合//1.2.1获取class目录下的配置文件
ClassLoader classLoader = ReflectTest.class.getClassLoader();
InputStream is= classLoader.getResourceAsStream("pro.properties");
pro.load(is);//2.获取配置文件中定义的数据
String className = pro.getProperty("className");
String methodName= pro.getProperty("methodName");//3.加载该类进内存
Class cls =Class.forName(className);//4.创建对象
Object obj =cls.newInstance();//5.获取方法对象
Method method =cls.getMethod(methodName);//6.执行方法
method.invoke(obj);
}
}
运行ReflectTest的结果:
如果想要读取不同类的不同方法,不需要修改ReflecTest的代码,只要修改配置文件pro.properties的内容即可,例如,将代码修改如下:
className =cn.itcast.domain.Person
methodName= eat
运行ReflectTest的结果:
PS:后来想到Person中还有一个有参的eat方法,实现调用的方法:将ReflectTest中下列语句:
//5.获取方法对象
Method method =cls.getMethod(methodName);//6.执行方法
method.invoke(obj);
修改为:
//5.获取方法对象
Method method = cls.getMethod(methodName,String.class);//6.执行方法
method.invoke(obj,"饭");
运行ReflectTest的结果:
2.注解