您的位置:首页 > 编程语言 > Java开发

javabean的内省操作

2014-11-01 19:17 176 查看
public class IntroSpectorDemo {
public static void main(String[] args) throws Exception {
BeanEntity entity = new BeanEntity(21, "hxl");
String firstProperty = "name";
String secondProperty = "age";
//通过内省操作javabean的第一种方式
PropertyDescriptor pd = new PropertyDescriptor(firstProperty,entity.getClass());
Method readMethod = pd.getReadMethod();
Object retVal = readMethod.invoke(entity);
System.out.println(retVal);
//通过内省操作javabean的第二种方式
BeanInfo beanInfo = Introspector.getBeanInfo(entity.getClass());
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for(PropertyDescriptor prd : pds) {
if(secondProperty.equals(prd.getName())) {
Method method = prd.getReadMethod();
Object val = method.invoke(entity);
System.out.println(val);
break;
}
}
}
static class BeanEntity {
private int age;
private String name;

public BeanEntity(int age, String name) {
this.age = age;
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}
}


我个人还是比较喜欢第一种方式,因为它很简单。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 内省 javabean