现在有Employee这个VO类:我们我们 需要新建很多的对象,为了设置属性,我们需要不端的调用getter和setter方法。假如这个类有十几个甚至几十个那么这件事就会变得更麻烦。
class Employee {
private String name;
public String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String toString() {
return " name: " + this.name + " sex: " + this.sex;
}
}
如果我们把要传的属性设置成Stringlei'类型一次传进去就会方面很多。
首先需要一个main类驱动这个程序。
public class OVDemo {
public static void main(String[] args) throws Exception {
String value = "employee.name:andy|employee.sex:man";//需要设置的属性的格式为:类名.属性名:属性值|类名.属性名:属性值...
EmpAction empAction = new EmpAction();//工厂类,创建对象
empAction.setValue(value);//设置属性
System.out.println(empAction.getEmployee());//取得对象后打印
}
}
然后然后创建一个工厂类。
class EmpAction {
Employee employee = new Employee();
public Employee getEmployee() {
return employee;
}
public void setValue(String value) throws Exception {
BeanOperation.setBeanValue(this, value);
}
}
实现BeanOperation类及setBeanValue方法。
class BeanOperation {
public static void setBeanValue(Object actionObject, String msg) throws Exception {
// 分离字符串 employee.name:andy|employee.age:21
String[] temp = msg.split("\\|");// employee.name:andy
for (int i = 0; i < temp.length; i++) {
String[] temp2 = temp[i].split("\\.");//
String[] temp3 = temp2[1].split(":");
Object realObj = getObject(actionObject, temp2[0]);
setValue(realObj, temp3[0], temp3[1]);
}
}
private static void setValue(Object realObj, String fieldName, String value) throws Exception {
Class<?> cls = realObj.getClass();
Field field = cls.getDeclaredField(fieldName);
if (field == null) {
field = cls.getDeclaredField(fieldName);
if (field == null) {
return;
}
}
String realClassName = "set" + initCap(fieldName);
Method method = cls.getMethod(realClassName, field.getType());
method.invoke(realObj, value);
}
private static Object getObject(Object actionObject, String fieldName) throws Exception {
Class<?> cls = actionObject.getClass();
if(cls.getField(fieldName)==null&&cls.getDeclaredField(fieldName)==null) {
//field取得的是所有public属性,declaredField取得的是所有本类属性,如果都为空,则不存在这个属性
return null;
}
String realClassName = "get" + initCap(fieldName);
Method method = cls.getMethod(realClassName);
Object obj = method.invoke(actionObject);
return obj;
}
private static String initCap(String string) {
// 将字符串的首字母大写
return string.substring(0, 1).toUpperCase() + string.substring(1, string.length());
}
}
以上代码即可完成反射与单级OV的操作。