使用內省的方式操作JavaBean
import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * 使用內省的方式操作JavaBean */ public class IntroSpectorTest { public static void main(String[] args) throws Exception { ReflectPoint reflectPoint = new ReflectPoint(3,7); //調用JavaBean中方法的傳統作法 Class classz = reflectPoint.getClass(); Field[] fields = classz.getDeclaredFields(); for (Field field : fields) { String name = "set" + field.getName().toUpperCase(); Method method = classz.getMethod(name, int.class); method.invoke(reflectPoint, 3); } System.out.println(reflectPoint); //使用內省的方式調用JavaBean的方法 String propertyName = "x"; //獲得屬性x的值 Object retVal = getProperty2(reflectPoint, propertyName); System.out.println(retVal); //設置屬性x的值 setProperty(reflectPoint, propertyName,10); System.out.println(reflectPoint.getX()); } /** * 設置屬性的值 * @param obj 屬性所屬的對象 * @param propertyName 屬性名 * @param propertyValue 屬性值 */ private static void setProperty(Object obj, String propertyName,Object propertyValue) throws Exception { PropertyDescriptor pd2 = new PropertyDescriptor(propertyName,obj.getClass()); Method setMethod = pd2.getWriteMethod(); setMethod.invoke(obj, propertyValue); } /** * 獲得對象的屬性值 * @param obj 屬性所屬的對象 * @param propertyName 屬性名 * @return 屬性的值 */ private static Object getProperty(Object obj, String propertyName) throws Exception { PropertyDescriptor pd = new PropertyDescriptor(propertyName,obj.getClass()); Method getMethod = pd.getReadMethod(); //獲得get方法 Object retVal = getMethod.invoke(obj); return retVal; } /** * 使用內省操作javabean * @param obj 屬性所屬的對象 * @param propertyName 屬性名 * @return 屬性的值 */ private static Object getProperty2(Object obj, String propertyName) throws Exception { Object retVal = null; BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor pd : pds) { if (pd.getName().equals(propertyName)) { Method getMethod = pd.getReadMethod(); retVal = getMethod.invoke(obj); break; } } return retVal; } }
最後更新:2017-04-02 22:16:20