package com.fly.intrespect;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import org.junit.Test;
//使用内省api操作bean的属性
public class Demo1 {
//得到bean的所有属性
@Test
public void test1() throws Exception {
//对person类进行内省
BeanInfo info = Introspector.getBeanInfo(Person.class, Object.class);
//获取bean所有的属性
PropertyDescriptor[] pds = info.getPropertyDescriptors();
for(PropertyDescriptor pd : pds) {
System.out.println(pd.getName());
}
}
//操纵bean的指定属性:age
@Test
public void test2() throws Exception {
Person p = new Person();
PropertyDescriptor pd = new PropertyDescriptor("age", Person.class);
//得到属性的写方法,为属性赋值
Method method = pd.getWriteMethod(); //public void setAge(11);
method.invoke(p, 12);
//获取属性的值
method = pd.getReadMethod(); //public int getAge()
System.out.println(method.invoke(p, null));
}
//获取属性的类型
@Test
public void test3() throws Exception {
Person p = new Person();
PropertyDescriptor pd = new PropertyDescriptor("age", Person.class);
System.out.println(pd.getPropertyType());
}
}
内省
最新推荐文章于 2022-04-26 21:12:58 发布
使用内省api操纵bean的属性。
2149

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



