JavaBean
内省主要用于对JavaBean进行操作二:通过Introspector类获得Bean对象的BeanInfo,然后通过BeanInfo来获取属性的描述器(PropertyDescriptor),通过这个属性描述器就可以获取某个属性对应的getter/setter方法,然后通过反射机制来调用这些方法。
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.beans.*; public class Test02 { public static void main(String[] args) throws Exception { method1(); method2(); } private static void method1() throws IntrospectionException, IllegalAccessException, InvocationTargetException { ReflectPoint pt1 = new ReflectPoint(3); String propertyName = "x"; //"x"-->"X"-->"getX"-->MethodGetX--> PropertyDescriptor pd =new PropertyDescriptor(propertyName,pt1.getClass());//属性描述符 Method methodGetX = pd.getReadMethod(); Object retVal=methodGetX.invoke(pt1); System.out.println(retVal); Method methodSetX = pd.getWriteMethod(); methodSetX.invoke(pt1,7); System.out.println(pt1.getX()); } private static void method2() throws IntrospectionException, IllegalAccessException, InvocationTargetException { ReflectPoint pt1 = new ReflectPoint(3); String propertyName = "x"; //"x"-->"X"-->"getX"-->MethodGetX--> BeanInfo beanInfo = Introspector.getBeanInfo(pt1.getClass()); PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); Object retVal = null; for(PropertyDescriptor pd : pds){ if(pd.getName().equals(propertyName)) { Method methodGetX = pd.getReadMethod(); retVal = methodGetX.invoke(pt1); break; } } System.out.println(retVal); } } class ReflectPoint { private int x; public ReflectPoint(int x) { super(); this.x = x; } public int getX() { return x; } public void setX(int x) { this.x = x; } }
2,BeanUtils
BeanUtils与PropertyUtils的相同点:②、PropertyUtils速度更快一些,而BeanUtils得速度比较慢