最近在学习JavaBean下面是我的一些总结,如果有错的希望大家指出来
package itcast.Test5;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.crypto.spec.PSource;
import org.apache.commons.beanutils.BeanUtils;
/*5、写一个方法,public void setProperty(Object obj, String propertyName, Object value){},
此方法可将obj对象中名为propertyName的属性的值设置为value。*/
//这题中用了内省的简单应用,理解到了JavaBean中setProperty()方法和getProperty()方法的实现
public class SetPropertyTest {
/**
* @param args
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalAccessException
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Point pt1 = new Point(3, 5);
String propertyName = "x";
Object value = 7;
getProperty(pt1, propertyName);
setProperty(pt1, propertyName, value);
//下面是使用BeanUtil工具包进行set和get属性的值
/*//System.out.println(BeanUtils.getProperty(pt1, propertyName));
BeanUtils.setProperty(pt1, propertyName, "9");
System.out.println(pt1.getX());
//System.out.println(pt1.getX());
*/ }
//setProperty()方法的实现
private static void setProperty(Object object, String propertyName, Object value) {
try {
//使用java.beans包中的PropertyDescriptor(属性操作符类)
PropertyDescriptor pd2 = new PropertyDescriptor(propertyName, object.getClass());
//通过反射来得到Point这个javabean的set方法
Method methodSetX = pd2.getWriteMethod();//getWriteMethod()得到JavaBean中可写的方法也就是set方法
methodSetX.invoke(object,value);//对方法进行赋值设置
} catch (Exception e) {
// TODO: handle exception
}
}
//getProperty()方法的实现
private static void getProperty(Object object, String propertyName) {
try {
PropertyDescriptor pd1 = new PropertyDescriptor(propertyName, object.getClass());
Method methodGetX = pd1.getReadMethod();
Object retVal = methodGetX.invoke(object);
System.out.println(retVal);
//下面所注析的时一种比较复杂的方法来获得JavaBean中的属性值
/* BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass());
//通过beanInfo对象调用getPropertyDescriptors()方法来获得所有的属性描述
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
Object retVal = null;
通过上面的操作得到了对JavaBean中的所有的属性的描述,下面就对所有的属性进行迭代,通过每个属性的getName()方法来得到属性名,
和我要找的那个属性名来进行比较,如果找到了,就进行相应的操作
for (PropertyDescriptor pd : pds) {
if(pd.getName().equals(propertyName)){
Method methodGetX = pd.getReadMethod();
retVal = methodGetX.invoke(object);
break;
}
}*/
//System.out.println(retVal);
} catch (Exception e) {
// TODO: handle exception
}
}
}
class Point {
private int x;
private int 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;
}
}