既然内省是作用于javaBean的,那么我们先提供一个JavaBean类,本例为UserBean.java
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中的方法时很管用。
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); } }
这两种方法均可以用来作为javaBean的内省操作