- package cn.itast;
- 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;
- import org.apache.commons.beanutils.BeanUtils;
- public class IntroSpector {
- public static void main(String[] args) throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
- // TODO Auto-generated method stub
- ReflectPoint pt1 = new ReflectPoint(3, 5);
-
- String propertyName = "x";
- //"x"-->"X"-->"getX"-->methodGetX-->
- Object retVal = getProperty(pt1, propertyName);
- System.out.println(retVal);
-
- Object value = 7;
- setProperty(pt1, propertyName, value);
- BeanUtils.getProperty(pt1,"x");
- System.out.println(pt1.getX());
- }
- private static void setProperty(ReflectPoint pt1, String propertyName,
- Object value) throws IntrospectionException,
- IllegalAccessException, InvocationTargetException {
- PropertyDescriptor pd2 = new PropertyDescriptor(propertyName, pt1.getClass());
- Method methodSetX = pd2.getWriteMethod();
- methodSetX.invoke(pt1,value);
- }j
- private static Object getProperty(Object pt1, String propertyName)
- throws IntrospectionException, IllegalAccessException,
- InvocationTargetException {
- /*PropertyDescriptor pd = new PropertyDescriptor(propertyName, pt1.getClass());
- Method methodGetX = pd.getReadMethod();
- Object retVal = methodGetX.invoke(pt1);*/
- BeanInfo beanInfo = Introspector.getBeanInfo(pt1.getClass());
- PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
- Object retVal = null;
- for(PropertyDescriptor pd : pds){
- if(pd.getName().equals(propertyName)){
- Method methodGetX = pd.getReadMethod();
- retVal = methodGetX.invoke(pt1);
- break;
- }
- }
-
-
- return retVal;
- }
- }
复制代码
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at cn.itast.IntroSpector.main(IntroSpector.java:14)
报上面的异常,昨天也是这个问题,14行就是主函数声明的那一行
|