什么是反射
反射:(reflection):在运行时期,动态地去获取类中的信息(类的信息,方法信息,构造器信息,字段等信息进行操作);
获取字节码实例有三种方式
1. 类名.class
2. 类的对象.getClass()
3. Class.forName(“类的全限定名”)
public class User {
protected String id;
protected int revision;
protected String firstName;
protected String lastName;
protected String email;
protected String password;
public User() {
super();
// TODO Auto-generated constructor stub
}
private User(String id, String firstName) {
super();
this.id = id;
this.firstName = firstName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getRevision() {
return revision;
}
public void setRevision(int revision) {
this.revision = revision;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
通过包名获取类,
public static void main(String[] args) {
try {
Class<?> ff= Class.forName("com.ww.model.User");
//无参构造获取类
com.ww.model.User obj= (com.ww.model.User)ff.newInstance();//必须保证类中有一个无参数公共构造函数 必须是公共,不能是私有,
//有参构造获取类
Constructor<?> ffh=ff.getConstructor(String.class,String.class);//获取指定的公共构造函数, 如果构造函数有参数,传递的是参数的字节码实例.必须是公共,不能是私有
com.ww.model.User ff555=(com.ww.model.User)ffh.newInstance("1","22222");
System.out.println(ff555.getId()+"======="+ff555.getFirstName()+"=========================");
//获取属性赋值
Field ffg= ff.getDeclaredField("id");//id 如果不是公有属性,就必须设置权限,
ffg.setAccessible(true);
ffg.set(obj, "8999999");
System.out.println(obj.getId());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Field[] | getFields() 获取当前Class所表示类中所有的public的字段,包括继承的字段. |
Field[] | getDeclaredFields() 获取当前Class所表示类中所有的字段,不包括继承的字段. |
Field | getField(String name) 获取当前Class所表示类中 |
Field | getDeclaredField(String name) :获取当前Class所表示类中该fieldName名字的字段,不包括继承的字段. |
通过反射应用,aop ,自定义注解
@Aspect
@Component
public class TestAspect {
@AfterReturning("@annotation(com.ww.model.testzj)")
public void test(JoinPoint jp) {
//获取类的字节码对象,通过字节码对象获取方法信息
Class<?> targetCls=jp.getTarget().getClass();
//获取方法签名(通过此签名获取目标方法信息)
MethodSignature signature = (MethodSignature) jp.getSignature();
Method method = signature.getMethod();
testzj myAnnotation = method.getAnnotation(testzj.class);
System.out.println(myAnnotation.name());
}
}