反射:框架设计的灵魂
什么是反射?
将类的各个组成部分(成员变量,构造函数,方法)封装为其他对象
Java代码在计算机中经历的三个阶段
案例
- 配置文件
className=day01.reflect.Car
methodName=carMethod
- 代码
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
public class PersonOrCar {
public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
//创建配置对象
Properties properties = new Properties();
//创建类加载器
ClassLoader classLoader = PersonOrCar.class.getClassLoader();
//通过类加载器,读取配置文件并转化为字节流
InputStream resourceAsStream = classLoader.getResourceAsStream("config.properties");
//载入配置文件
properties.load(resourceAsStream);
//读取配置文件中的类名和方法名
String className = properties.getProperty("className");
String methodName = properties.getProperty("methodName");
//加载该类进入到内存中运行
Class aClass = Class.forName(className);
//创建该类的一个对象
Object newObj = aClass.newInstance();
//获取方法对象
Method method = aClass.getMethod(methodName);
//运行该类的方法
method.invoke(newObj);
}
}