public class Demo1 {
//得到bean所有属性
@Test
public void test1() throws IntrospectionException{
BeanInfo info=Introspector.getBeanInfo(Person.class);
//去掉Object里的属性
BeanInfo info2=Introspector.getBeanInfo(Person.class,Object.class);
PropertyDescriptor[] pds=info.getPropertyDescriptors();
for(PropertyDescriptor pd:pds){
System.out.println(pd.getName());
//ab age class name password
}
}
//操纵bean的指定属性:age
@Test
public void test2() throws Exception{
Person p=new Person();
PropertyDescriptor pd=new PropertyDescriptor("age", Person.class);
//得到属性的写方法,为属性赋值
Method method=pd.getWriteMethod();
method.invoke(p, 45);
System.out.println(p.getAge());//45
//获取属性的值
method=pd.getReadMethod();
System.out.println(method.invoke(p, null));//45
}
//高级内容,获取当前操作的属性的类型
@Test
public void test3() throws Exception{
Person p=new Person();
PropertyDescriptor pd=new PropertyDescriptor("age", Person.class);
//得到属性的写方法,为属性赋值
Method method=pd.getWriteMethod();
System.out.println(pd.getPropertyType());//int
method.invoke(p, 45);
System.out.println(p.getAge());//45
//获取属性的值
method=pd.getReadMethod();
System.out.println(method.invoke(p, null));//45
}
}
//得到bean所有属性
@Test
public void test1() throws IntrospectionException{
BeanInfo info=Introspector.getBeanInfo(Person.class);
//去掉Object里的属性
BeanInfo info2=Introspector.getBeanInfo(Person.class,Object.class);
PropertyDescriptor[] pds=info.getPropertyDescriptors();
for(PropertyDescriptor pd:pds){
System.out.println(pd.getName());
//ab age class name password
}
}
//操纵bean的指定属性:age
@Test
public void test2() throws Exception{
Person p=new Person();
PropertyDescriptor pd=new PropertyDescriptor("age", Person.class);
//得到属性的写方法,为属性赋值
Method method=pd.getWriteMethod();
method.invoke(p, 45);
System.out.println(p.getAge());//45
//获取属性的值
method=pd.getReadMethod();
System.out.println(method.invoke(p, null));//45
}
//高级内容,获取当前操作的属性的类型
@Test
public void test3() throws Exception{
Person p=new Person();
PropertyDescriptor pd=new PropertyDescriptor("age", Person.class);
//得到属性的写方法,为属性赋值
Method method=pd.getWriteMethod();
System.out.println(pd.getPropertyType());//int
method.invoke(p, 45);
System.out.println(p.getAge());//45
//获取属性的值
method=pd.getReadMethod();
System.out.println(method.invoke(p, null));//45
}
}
本文通过具体示例介绍了如何使用Java反射API来获取和操作对象的属性。首先展示了如何获取类的所有属性并排除Object类的属性,然后演示了如何操作特定属性(如age),包括设置和获取属性值以及获取属性的数据类型。

2万+

被折叠的 条评论
为什么被折叠?



