注解与反射
反射
什么是反射
一个类被加载后,类的整个结构都封装在Class整个对象中
双亲委派机制:自上而下,从根加载器开始看,然后到系统加载器,到自定义加载器
Method与invoke
Method就是获取方法,invoke就是实现这个方法
Testqq
实体类
package com.test;
public class Testqq {
public String namee;
public Integer age;
public String getNamee() {
return namee;
}
public void setNamee(String namee) {
this.namee = namee;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
Testww
实现类
package com.test;
import org.junit.Test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Testww {
@Test
public void tsee() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Testqq testqq = new Testqq();
Class<?> aClass = Class.forName("com.test.Testqq");
Method setNamee = aClass.getMethod("setNamee", String.class);
setNamee.invoke(testqq,"20");
Method getNamee = aClass.getMethod("getNamee");
System.out.println(getNamee.invoke(testqq));
}
}