2段简单的JavaBean代码演示了简单内省操作以及复杂内省操作 。
1、简单内省操作
package me.test;
import java.lang.reflect.*; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; public class IntroSpectorTest { public static void main(String []args) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { JavaBeanTest t=new JavaBeanTest() ; t.setX(10); PropertyDescriptor d=new PropertyDescriptor("X",JavaBeanTest.class); setProperty(t, d); Object val = getProperty(t, d); System.out.println(val); }private static Object getProperty(JavaBeanTest t, PropertyDescriptor d)
throws IllegalAccessException, InvocationTargetException { Method mr=d.getReadMethod() ; Object val=mr.invoke(t); return val; }private static void setProperty(JavaBeanTest t, PropertyDescriptor d)
throws IllegalAccessException, InvocationTargetException { Method mw=d.getWriteMethod() ; mw.invoke(t, 5) ; }}
class JavaBeanTest { private int x ; public void setX(int x) { this.x=x ; } public int getX() { return this.x ; } }
2、复杂内省操作 BeanInfo类 Introspector类的使用
package me.test;
import java.lang.reflect.*; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; public class IntroSpectorTest { public static void main(String []args) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { JavaBeanTest t=new JavaBeanTest(10) ; PropertyDescriptor d=new PropertyDescriptor("x",JavaBeanTest.class); setProperty(t, d); Object val = getProperty(t, d); System.out.println(val); }private static Object getProperty(JavaBeanTest t, PropertyDescriptor d)
throws IllegalAccessException, InvocationTargetException, IntrospectionException { BeanInfo beanInfo=Introspector.getBeanInfo(t.getClass()) ; PropertyDescriptor pt[]=beanInfo.getPropertyDescriptors() ; for(PropertyDescriptor tem:pt) { if(tem.getName().equals(d.getName())) { Method mr=tem.getReadMethod() ; Object val=mr.invoke(t) ; return val ; } } return null;}
private static void setProperty(JavaBeanTest t, PropertyDescriptor d)
throws IllegalAccessException, InvocationTargetException, IntrospectionException { BeanInfo beanInfo=Introspector.getBeanInfo(t.getClass() ) ; //把JavaBeanTest的对象当做JavaBean看有什么信息封装在BeanInfo中 PropertyDescriptor [] pd=beanInfo.getPropertyDescriptors() ; //Get All Properties From BeanInfo Class for(PropertyDescriptor tem:pd) { if(tem.getName().equals(d.getName())) { Method mw=tem.getWriteMethod() ; mw.invoke(t, 50) ; break ; } } }}
class JavaBeanTest { private int x ; public JavaBeanTest(int x) { this.x=x ; } public void setX(int x) { this.x=x ; } public int getX() { return this.x ; } }