个普通类符合JavaBean的规则,既可当作一个JavaBean来看,也可当作普通类来用。
JavaBean规则:
1、类的属性是private
2、类的属性符合JavaBean规则
3、类的属性由get和set方法获取和设置
class Person{ //bean class
private String name;
private int age;
public BeanClass(String name, int age){
this.name = name;
this.age = age;
}
public String getName(){ return name;}
public int getAge(){ return age;}
public void setName(String name){ this.name = name;}
public void setAge(int age){ this.age = age;}
}
//main
//属性描述符:
Person person = new Person("Yang" , 25);
String propertyName = "name";
PropertyDescriptor personPdesc = new PropertyDescriptor(propertyName, person.getClass());
Method methodGetName = personPdesc.getReadMethod();
Object retNameVal = methodGetName.invoke(person);
Method methodSetName = personPdecs.getWriteMethod();
methodSetName.invoke(persion, "JUN");
//内省器:复杂方法,不推荐
Person person = new Person("Yang" , 25);
String propertyName = "name";
BeanInfo beanInfo = Introspector.getBeanInfo(person.getClass());
PropertyDescriptor[] personPdescs = beanInfo.getPropertyDecriptors(); // All,not one
Object retNameVal = null;
for(PropertyDescriptor pd : personPdescs){ //需要逐一遍历
if(pd.getName().equals(propertyName)){
Method methodGetName = pd.getReadMethod();
retNameVal = methodGetName.invoke(person);
}
}
//使用Beanutils工具:下载相关包,并将包拷贝到工程下,右键-build path
|
|