- import java.beans.BeanInfo;
- import java.beans.Introspector;
- import java.beans.PropertyDescriptor;
- import java.lang.reflect.Field;
- import java.lang.reflect.Method;
-
- public class IntroSpectorTest {
-
- public static void main(String[] args) throws Exception {
- ReflectPoint reflectPoint = new ReflectPoint(3,7);
-
-
- 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);
-
-
- String propertyName = "x";
-
- Object retVal = getProperty2(reflectPoint, propertyName);
- System.out.println(retVal);
-
- setProperty(reflectPoint, propertyName,10);
- System.out.println(reflectPoint.getX());
-
- }
-
-
- 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);
- }
-
-
- private static Object getProperty(Object obj, String propertyName) throws Exception {
- PropertyDescriptor pd = new PropertyDescriptor(propertyName,obj.getClass());
- Method getMethod = pd.getReadMethod();
- Object retVal = getMethod.invoke(obj);
- return retVal;
- }
-
-
- 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;
- }
- }
使用内省的方式操作JavaBean
原文:http://www.cnblogs.com/starhu/p/5605396.html