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 IntroSpectorTest {
public static void main(String[] args) throws Exception{
Point p1 = new Point(2, 3);
String protertyName = "x";
System.out.println(BeanUtils.getProperty(p1, "x"));
getProperty(p1, protertyName);
int newValue = 7;
setProperty(p1, protertyName, newValue);
System.out.println(p1.getX());
System.out.println(p1.toString());
}
private static void setProperty(Point p1, String protertyName, int newValue)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
PropertyDescriptor pd1 = new PropertyDescriptor(protertyName, p1.getClass());
Method methodSetX = pd1.getWriteMethod();
methodSetX.invoke(p1, newValue);
}
private static void getProperty(Object p1, String protertyName)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
PropertyDescriptor pd = new PropertyDescriptor(protertyName, p1.getClass());
Method methodGetX = pd.getReadMethod();
Object retVal = methodGetX.invoke(p1);
System.out.println(retVal);
// 此为第二种实现方式,比较麻烦,
/* BeanInfo beanInfo = Introspector.getBeanInfo(p1.getClass());
PropertyDescriptor [] pds = beanInfo.getPropertyDescriptors();
for(PropertyDescriptor pd1 : pds){
if((pd1.toString()).equals(protertyName)){
Method method = pd1.getReadMethod();
System.out.println(method.invoke(pd1));
break;
}
}*/
}
}
class Point{
private int x,y;
public Point(int x, int y) {
super();
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
@Override
public String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
}[/code]
这个会出错,但是如果不用BeanUtils包,用我自己写的方法是OK的,怎么破?
还有,我下载了个beanUtils包,和当年老师用的那个不太一样了,这里边一共
commons-beanutils-1.9.2.jar
commons-beanutils-1.9.2-javadoc.jar
commons-beanutils-1.9.2-sources.jar
commons-beanutils-1.9.2-tests.jar
commons-beanutils-1.9.2-test-sources.jar
这么多jar包,我改用哪个?望大神不吝赐教...对了,能告诉我每个包都是什么最好,有啥区别? |
|