反射技術實際是已經可以徹底知足咱們對javaBean的各類操做了,可是爲了方便JDK仍是爲咱們提供了一套操縱JavaBean的API,咱們稱這套API爲內省操做(Introspector),下面示範一下一般的兩種內省操做. java
既然內省是做用於javaBean的,那麼咱們先提供一個JavaBean類,本例爲UserBean.java this
package net.csdn.blog; public class UserBean { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
方法一:第一種方法爲較繁瑣的一種方法,但一般在批量操縱javaBean中的方法時很管用。 spa
package net.csdn.blog; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class UserBeanHandlerOne { public static void main(String args[]) { UserBean user = new UserBean(); try { handleBean(user); } catch (Exception e) { e.printStackTrace(); } } private static void handleBean(UserBean user) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { BeanInfo bi = Introspector.getBeanInfo(user.getClass()); PropertyDescriptor[] pd = bi.getPropertyDescriptors(); for (PropertyDescriptor p : pd) { String attrName=p.getName(); if(attrName.equals("name")||attrName.equals("age")){ Method writeMethod=p.getWriteMethod();//獲得set方法 Class clazz[]=writeMethod.getParameterTypes(); if(clazz[0]==int.class) writeMethod.invoke(user, 20); else writeMethod.invoke(user, "peter");//執行set方法 Method readMethod = p.getReadMethod();//獲取get方法 Object obj = readMethod.invoke(user);//執行get方法 System.out.println(obj); } } } }
package net.csdn.blog; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class UserBeanHandlerTwo { public static void main(String args[]) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{ UserBean ub=new UserBean(); PropertyDescriptor pd=new PropertyDescriptor("name",UserBean.class); Method writeMethod=pd.getWriteMethod(); writeMethod.invoke(ub,"peter"); Method readMethod=pd.getReadMethod(); Object str=readMethod.invoke(ub); System.out.println(str); } }