JAVA中反射机制
2020-04-21 本文已影响0人
程序员大春
内省(Introspector) 是Java 语言对JavaBean类属性、事件的一种缺省处理方法。
JavaBean是一种特殊的类,主要用于传递数据信息,这种类中的方法主要用于访问私有的字段,且方法名符合某种命名规则。如果在两个模块之间传递信息,可以将信息封装进JavaBean中,这种对象称为“值对象”(Value Object),或“VO”。方法比较少。这些信息储存在类的私有变量中,通过set()、get()获得。
例如类UserInfo :
package com.peidasoft.instrospector;
public class UserInfo {
private long userId;
private String userName;
private int age;
private String emailAddress;
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
}
在类UserInfo中有属性userName,那我们可以通过getUserName, setUserName来得到其值或者设置新的值。通过getUserName/setUserName来访问userName属性,这就是默认的规则。Java JDK中提供了一套API用来访问某个属性的getter/setter方法,这就是内省。
JDK内省类库
PropertyDescriptor类:(属性描述器)
PropertyDescriptor类表示JavaBean类通过存储器导出一个属性。主要方法:
- getPropertyType(),获得属性的Class对象;
- getReadMethod(),获得用于读取属性值的方法;
- getWriteMethod(),获得用于写入属性值的方法;
- hashCode(),获取对象的哈希值;
- setReadMethod(Method readMethod),设置用于读取属性值的方法;
- setWriteMethod(Method writeMethod),设置用于写入属性值的方法。
package com.peidasoft.instrospector;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
public class BeanInfoUtil {
// 设置bean的某个属性值
public static void setProperty(UserInfo userInfo, String userName) throws Exception {
// 获取bean的某个属性的描述符
PropertyDescriptor propDesc = new PropertyDescriptor(userName, UserInfo.class);
// 获得用于写入属性值的方法
Method methodSetUserName = propDesc.getWriteMethod();
// 写入属性值
methodSetUserName.invoke(userInfo, "wong");
System.out.println("set userName:" + userInfo.getUserName());
}
// 获取bean的某个属性值
public static void getProperty(UserInfo userInfo, String userName) throws Exception {
// 获取Bean的某个属性的描述符
PropertyDescriptor proDescriptor = new PropertyDescriptor(userName, UserInfo.class);
// 获得用于读取属性值的方法
Method methodGetUserName = proDescriptor.getReadMethod();
// 读取属性值
Object objUserName = methodGetUserName.invoke(userInfo);
System.out.println("get userName:" + objUserName.toString());
}
}