对JavaBean内省的操作张老师演示了用PropertyDescriptor编写一个方法setProperty()来给一个实例对象的属性赋值。我用BeanInfo类来编写,编译的时候没有错误,就是运行的时候不能通过,我就是找不出愿意来,求助大家了。- import java.beans.*;
- import java.lang.reflect.Method;
- import java.beans.Introspector;
- public class SetProperty {
- private String name;
- private int 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;
- }
- public SetProperty(String name,int age)
- {
- this.name=name;
- this.age=age;
- }
- public void setProperty(Object obj, String propertyName, Object value) throws Exception
- {
- BeanInfo beanInfo=Introspector.getBeanInfo(obj.getClass());
- PropertyDescriptor[] pds=beanInfo.getPropertyDescriptors();
- for(PropertyDescriptor pd:pds)
- {
- if(pd.getName().equals(propertyName));
- {
- Method methodSet=pd.getWriteMethod();
- methodSet.invoke(obj, value);
- }
- }
- }
- public static void main(String[] args) {
- try
- {
- SetProperty setP=new SetProperty("Tom",20);
- setP.setProperty(setP,"name","Tom");
- setP.setProperty(setP,"age",30);
- System.out.println("name:"+setP.getName());
- System.out.println("age:"+setP.getAge());
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- }
- }
复制代码 |
|