Javabean:
package instroSpect;
import java.util.Date;
public class Javabean {
int x;
int y;
Date date = new Date();
/**
* @return the date
*/
public Date getDate() {
return date;
}
/**
* @param date
* the date to set
*/
public void setDate(Date date) {
this.date = date;
}
public Javabean(int x, int y) {
this.x = x;
this.y = y;
}
/**
* @return the x
*/
public int getX() {
return x;
}
/**
* @param x
* the x to set
*/
public void setX(int x) {
this.x = x;
}
/**
* @return the y
*/
public int getY() {
return y;
}
/**
* @param y
* the y to set
*/
public void setY(int y) {
this.y = y;
}
}
package instroSpect;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
/**
* 对javaBean的简单内省操作
* @author xiaoyu
*
*/
public class InstroSpectTest {
public static void main(String[] args) throws Exception{
Javabean javabean=new Javabean(3, 5);
//读取 x
String propertyName="x";
Object retVal=getProperty(javabean, propertyName);
System.out.println(retVal);
//写操作
Object value=7;
setProperty(javabean, propertyName, value);
System.out.println(javabean.getX());
//使用BeanUtils工具来操作 javabean,保存值和设置值都是通过String 类型来操作
String xValue=BeanUtils.getProperty(javabean, propertyName);
System.out.println("通过BeanUtils的到的值:"+xValue);
BeanUtils.setProperty(javabean, "x", "9");
//使用BeanUtils 来操作时间(Date)属性
BeanUtils.setProperty(javabean, "date.time", "1002");// Date 在javabean 中 必须 初始化
System.out.println(BeanUtils.getProperty(javabean, "date.time"));
//使用PropertyUtils操作就avabean,需要准确的数据类型
PropertyUtils.setProperty(javabean, "y", 11);
System.out.println(PropertyUtils.getProperty(javabean, "y"));
System.out.println(PropertyUtils.getProperty(javabean, "y").getClass().getName());
}
private static void setProperty(Javabean javabean, String propertyName,
Object value) throws IntrospectionException,
IllegalAccessException, InvocationTargetException {
PropertyDescriptor pDescriptor=new PropertyDescriptor(propertyName, javabean.getClass());
Method methodSetX=pDescriptor.getWriteMethod();
methodSetX.invoke(javabean, value);
}
private static Object getProperty(Object javabean, String propertyName)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
PropertyDescriptor temPropertyDescriptor=new PropertyDescriptor(propertyName, javabean.getClass());
Method tempmMethod=temPropertyDescriptor.getReadMethod();
Object returnValue=tempmMethod.invoke(javabean);
return returnValue;
}
}
结果:
3
7
通过BeanUtils的到的值:7
1002
11
java.lang.Integer