Java反射机制
在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法;这种动态获取的以及动态调用对象的方法的功能称为Java的反射机制。
比如:下面的通过配置文件来创建一个类,然后根据配置文件的方法来执行这个方法的这个例子
re.properties
classfullpath=com.hspedu.Cat
method=cry
public class Cat {
private String name = "招财猫";
public int age = 10; //public的
public Cat() {} //无参构造器
public Cat(String name) {
this.name = name;
}
public void hi() { //常用方法
//System.out.println("hi " + name);
}
public void cry() { //常用方法
System.out.println(name + " 喵喵叫..");
}
}
public class ReflectionQuestion {
public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
//根据配置文件 re.properties 指定信息, 创建Cat对象并调用方法hi
//老韩回忆
//传统的方式 new 对象 -》 调用方法
// Cat cat = new Cat();
// cat.hi(); ===> cat.cry() 修改源码.
//我们尝试做一做 -> 明白反射
//1. 使用Properties 类, 可以读写配置文件
Properties properties = new Properties();
properties.load(new FileInputStream("D:\\cache\\re.properties"));
String classfullpath = properties.get("classfullpath").toString();//"com.hspedu.Cat"
String methodName = properties.get("method").toString();//"hi"
System.out.println("classfullpath=" + classfullpath);
System.out.println("method=" + methodName);
//2. 创建对象 , 传统的方法,行不通 =》 反射机制
//new classfullpath();
//3. 使用反射机制解决
//(1) 加载类, 返回Class类型的对象cls
Class cls = Class.forName(classfullpath);
//(2) 通过 cls 得到你加载的类 com.hspedu.Cat 的对象实例
Object o = cls.newInstance();
System.out.println("o的运行类型=" + o.getClass()); //运行类型
//(3) 通过 cls 得到你加载的类 com.hspedu.Cat 的 methodName"hi" 的方法对象
// 即:在反射中,可以把方法视为对象(万物皆对象)
Method method1 = cls.getMethod(methodName);
//(4) 通过method1 调用方法: 即通过方法对象来实现调用方法
System.out.println("=============================");
method1.invoke(o); //传统方法 对象.方法() , 反射机制 方法.invoke(对象)
}
}
网友评论