public class Emp {
private String name;
private String job;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
@Override
public String toString() {
return "Emp [name=" + name + ", 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.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class BeanOperation {
private BeanOperation() {
}
public static void setBeanValue(Object object, String msg) throws Exception {
String[] result = msg.split("\\|");
for (int i = 0; i < result.length; i++) {
String[] tmp = result[i].split(":");
String attribute = tmp[0];
String value = tmp[1];
String[] fields = attribute.split("\\.");
Object currentObject = getObject(object, result[0]);
setObjectValue(currentObject, result[1], tmp[1]);
}
}
public static String initCap(String str) {
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
public static Object getObject(Object obj, String attribute) throws NoSuchMethodException, SecurityException,
NoSuchFieldException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
String methodName = "get" + initCap(attribute);
Field field = obj.getClass().getDeclaredField(attribute);
if (field == null) {
field = obj.getClass().getField(attribute);
}
if (field == null) {
return null;
}
Method method = obj.getClass().getMethod(methodName);
return method.invoke(obj);
}
public static void setObjectValue(Object obj, String attribute, String value) throws Exception {
Field field = obj.getClass().getDeclaredField(attribute);
if (field == null) {
field = obj.getClass().getField(attribute);
}
if (field == null) {
return;
}
String methodName = "set" + initCap(attribute);
Method setmsthod = obj.getClass().getMethod(methodName, field.getType());
setmsthod.invoke(obj, value);
}
}
public class TestDemo {
public static void main(String[] args) throws Exception {
String value="emp.ename:yuisama|emp.job:JAVA CODER";
EmpAction empAction=new EmpAction();
empAction.setValue(value);
System.out.println(empAction.getEmp());
}
}