Point类(要操作的JavaBean类)
package test;
public class Point {
private double x;
private double y;
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
/**
* @param x
* @param y
*/
public Point(double x, double y) {
super();
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
}
BeanUtils包操作JavaBean类
package test;
import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.beanutils.BeanUtils;
public class MainTest {
public static void main(String[] args) throws IllegalArgumentException,
IntrospectionException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException {
Point p = new Point(3, 5);
System.out.println("变量: " + p);
System.out.println("p.getX() = : " + BeanUtils.getProperty(p, "x"));
System.out.println("");
System.out.println("第三个参数的变量类型是 double(Point类中x的变量类型)");
BeanUtils.setProperty(p, "x", 12);
System.out.println(p);
System.out.println("");
System.out.println("第三个参数的变量类型是 String(setProperty内部自动会转化成相应的变量的类型)");
BeanUtils.setProperty(p, "x", "13");
System.out.println(p);
System.out.println("");
Map<String, String> map = BeanUtils.describe(p);
System.out.println("describe方法调用获取map");
for (Entry<String, String> it : map.entrySet()) {
System.out.println(it.getKey() + "=" + it.getValue());
}
System.out.println("");
System.out.println("populate方法, 通过map变量赋值给JavaBean类");
HashMap<String, Double> set = new HashMap<String, Double>();
set.put("x", 1000.0);
set.put("y", 2000.0);
BeanUtils.populate(p, set);
System.out.println(p);
}
}