Java反射
什么是反射?
程序运行时,能够动态加载类,获得和执行其所有属性和方法。
如何读取一个类
方法一:
Class person = Person.class;
方法二:
try {
Class person = Class.forName("com.jane.Person");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
在实际开发中,方法二用得比较多,因为不需要显式获取一个类,可以很方面后期修改,算是一种解耦,保证开闭原则。
此外,方法二还能批量读取类。
比如下面这个例子
<root>
<className>com.jane.Person</className>
</root>
String name = Xml.getClassName();
try {
Class person = Class.forName(name);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
如果要实例化其他类,改一下xml的配置信息即可
动态生成类
Class personClass = Class.forName("Person");
Person person = personClass.newInstance();
jdk1.9后淘汰上面这种方法,因为只能调用无参构造器;
一个例子
Persion.java
import java.util.Random;
/**
* @author: jane
* @CreateTime: 2020/4/28
* @Description:
*/
public class Person {
int id;
String name;
int age;
Person(){
}
Person(String name, int age){
this.name = name;
this.age = age;
//generate a random id
Random random = new Random();
this.id = random.nextInt(100000000);
}
Person(int id, String name, int age){
this.id = id;
this.name = name;
this.age = age;
}
public void introduction(){
System.out.printf("Id:%d - Hello,my name is %s,and I'm %d years old.\n", id, name, age);
}
public int calAdd(int a, int b){
return a+b;
}
}
Client.java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author: jane
* @CreateTime: 2020/4/28
* @Description:
*/
public class Client {
public static void main(String[] args) {
Method[] methods = Person.class.getDeclaredMethods();//不会获取父类方法,除非重写
for(Method method : methods){
System.out.println("定义的方法:"+method.getName());
}
try {
Class<?> personClass = Class.forName("Person");
Person person = (Person)personClass.getDeclaredConstructor(String.class, int.class).newInstance("Jane", 22);
Method method1 = personClass.getDeclaredMethod("introduction");
method1.invoke(person);
Method method2 = personClass.getDeclaredMethod("calAdd", int.class, int.class);
int ans = (int)method2.invoke(person, 4, 7);
System.out.printf("计算结果:%d\n", ans);
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
e.printStackTrace();
}
}
}
定义的方法:introduction
定义的方法:calAdd
Id:7342458 - Hello,my name is Jane,and I'm 22 years old.
计算结果:11

浙公网安备 33010602011771号