- package cn.itcast.day1;
- import java.beans.BeanInfo;
- import java.beans.IntrospectionException;
- import java.beans.Introspector;
- import java.beans.MethodDescriptor;
- import java.beans.PropertyDescriptor;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- public class IntroSpectorTest {
- /**
- * IntroSpector:内省。
- * @param args
- */
- public static void main(String[] args) throws Exception{
- // TODO Auto-generated method stub
- ReflectPoint pt1 = new ReflectPoint(2, 3);
- //ReflectPoint类是自己定义的。看过视屏的都知道吧
-
- String propertyName = "x";
-
- Object retVal = getProperty(pt1, propertyName);
- System.out.println(retVal);
-
- Object val = 76;
- setProperty(pt1, propertyName, val);
- System.out.println(pt1.getX());
-
-
- }
- private static void setProperty(Object pt1, String propertyName,
- Object val) throws IntrospectionException, IllegalAccessException,
- InvocationTargetException {
- PropertyDescriptor pd = new PropertyDescriptor(propertyName, pt1.getClass());
- Method methodSet = pd.getWriteMethod();
- methodSet.invoke(pt1, val);
- }
- private static Object getProperty(Object pt1, String propertyName)
- throws IntrospectionException, IllegalAccessException,
- InvocationTargetException {
- PropertyDescriptor pd = new PropertyDescriptor(propertyName, pt1.getClass());
- Object retVal = pd.getReadMethod().invoke(pt1);
-
- /*[b]以下这个方法是张老师演示的,可是我运行的结果为null,并不是2!哪里错了?????[/b]
- Object retVal = null;
- BeanInfo beanInfo = Introspector.getBeanInfo(pt1.getClass());
- PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
-
- for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
- if(propertyDescriptor.getName().equals(propertyName))
- retVal = propertyDescriptor.getReadMethod().invoke(pt1);
- break;
- }*/
- return retVal;
- }
- }
复制代码 |