如:输入"emp.name:张三|emp.job:Linux Coder",输出对象Emp{name='张三', job='Linux Coder'}
public class Emp {
private String name;
private String job;
public String getName() {
return name;
}
@Override
public String toString() {
return "Emp{" +
"name='" + name + '\'' +
", job='" + job + '\'' +
'}';
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
}
public class EmpAction {
private Emp emp=new Emp();
public void setValue(String value) throws Exception {
BeanOperation.setBeanValue(this,value);
}
public Emp getEmp() {
return emp;
}
}
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
//工具类 不需要产生对象,因此构造方法私有化
public class BeanOperation {
private BeanOperation(){}
/**
*
* @param actionObj
* @param value emp.name:yuisa|emp.job:Linux Coder
*/
public static void setBeanValue(Object actionObj,String value) throws Exception {
//1.进行字符串拆分
String[] temp=value.split("\\|");
//temp[0]:emp.name:yuisa
for(int i=0;i<temp.length;i++){
String[] result=temp[i].split(":");
//result[0]:emp.name result[1]:yuisa
//取得真实要设置的内容
String realVal=result[1];
//取得要设置的真实类名称 emp
String realClassName=result[0].split("\\.")[0];
//取得要设置的属性名称 name
String attrName=result[0].split("\\.")[1];
//通过反射取得xxAction中的真实对象
Object realObj=getRealObject(actionObj,realClassName);
//1.取得emp class对象
Class<?> cls=realObj.getClass();
//2.取得setter方法对象
String setName="set"+initCap(attrName);
Method setMethod=cls.getDeclaredMethod(setName,String.class);
setMethod.invoke(realObj,realVal);
}
}
//取得真实操作的类对象
private static Object getRealObject(Object actionObj,String realClassName){
//取得action对象的class对象
Class<?> cls=actionObj.getClass();
//拼装getEmp方法名
String methodName="get"+initCap(realClassName);
Object realObj=null;
//取得method对象
try {
//取得getEmp的Method对象
Method method=cls.getMethod(methodName);
//相当于调用了empaction.getEmp()
realObj=method.invoke(actionObj);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return realObj;
}
//首字母大写
private static String initCap(String str){
return str.substring(0,1).toUpperCase()+str.substring(1);
}
}
public class Test {
public static void main(String[] args) throws Exception {
String value="emp.name:张三|emp.job:Linux Coder";
EmpAction empAction=new EmpAction();
empAction.setValue(value);
System.out.println(empAction.getEmp());
}
}
结果: