内省

来源:互联网 发布:网络搞笑猛虎下山图 编辑:程序博客网 时间:2024/05/29 05:14
使用内省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的所有属性@Testpublic 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@Testpublic 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));}//获取属性的类型@Testpublic void test3() throws Exception {Person p = new Person();PropertyDescriptor pd = new PropertyDescriptor("age", Person.class);System.out.println(pd.getPropertyType());}}


0 0
原创粉丝点击