您的位置:首页 > 其它

内省

2015-10-17 22:46 176 查看
使用内省api操纵bean的属性。

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());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: