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 java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
public class IntroSpectorTest {
public static void main(String[] args) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
ReflectPoint p1=new ReflectPoint(3,5);
String properyName="x";
// "x"==>"X"==>"getX"--->MethodGetX-->
Object retVal = getProperty(p1, properyName);
System.out.println(retVal);
setProperty(p1, properyName);
System.out.println(BeanUtils.getProperty(p1, "x").getClass().getName());
BeanUtils.setProperty(p1, "x", "9");
Method method= p1.getClass().getDeclaredMethod("getX",int.class);
method.setAccessible(true);
System.out.println(p1.getX()); //这段代码的问题getX报错,无权访问,问什么,我已经setsetAccessible(true);了呀,private int getX();
/* // java7新特性
// Map map={name:"zxx",age:18};// jdk1.7新特性
// BeanUtils.setProperty(map, "name", "lhm");
*/
BeanUtils.setProperty(p1, "birthday.time", "111" );
System.out.println(BeanUtils.getProperty(p1, "birthday.time"));
PropertyUtils.setProperty(p1, "x", 9);
System.out.println(PropertyUtils.getProperty(p1, "x").getClass().getName());
}
private static void setProperty(ReflectPoint p1, String properyName)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
PropertyDescriptor pd1=new PropertyDescriptor(properyName,p1.getClass());
Method methodSetX=pd1.getWriteMethod();
methodSetX.invoke(p1,7);
}
private static Object getProperty(ReflectPoint p1, String properyName)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
/* PropertyDescriptor pd=new PropertyDescriptor(properyName,p1.getClass());
Method methodGetX=pd.getReadMethod();
Object retVal=methodGetX.invoke(p1);
return retVal;*/
BeanInfo beanInfo=Introspector.getBeanInfo(p1.getClass());
PropertyDescriptor []pds=beanInfo.getPropertyDescriptors() ;
Object retVal=null;
for (PropertyDescriptor pd : pds) {
if(pd.getName().equals(properyName)){
Method methodGetX=pd.getReadMethod();
retVal=methodGetX.invoke(p1);
break;
}
}
return retVal;
}
}
该贴已经同步到 张强+的微博 |
|