简单Java类中的组成较为单一,在赋值中只需要通过反射考虑获取相应的Field与Method实例就可以实现赋值处理,课程主要讲解对于单个VO类实例化对象实现的属性赋值处理操作。
package com.apple.demo;
import java.lang.reflect.Field;
import java.lang.reflect.Method;;;
class ClassInstanceFactory{
private ClassInstanceFactory() {}
public static <T> T create(Class<?> clazz,String value) {
try {
Object obj = clazz.getDeclaredConstructor().newInstance();
BeanUtils.setValue(obj, value);
return (T) obj;
} catch (Exception e) {
return null;
}
}
}
class BeanUtils{
private BeanUtils() {}
public static void setValue(Object obj, String value) {
String results[] = value.split("\|");
for(int x=0;x<results.length;x++) {
String attval[] = results[x].split(":");
try {
Field field = obj.getClass().getDeclaredField(attval[0]);
Method setMethod = obj.getClass().getDeclaredMethod("set"+StringUtils.initcap(attval[0]), field.getType());
setMethod.invoke(obj, attval[1]);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
class StringUtils{
public static String initcap(String str) {
if(str == null || "".equals(str)) {
return str;
}
if(str.length() == 1) {
return str.toUpperCase();
}else {
return str.substring(0,1).toUpperCase()+str.substring(1);
}
}
}
class Emp{
private String ename;
private String job;
public String getEname() {
return this.ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getJob() {
return this.job;
}
public void setJob(String job) {
this.job = job;
}
}
public class JavaReflectDemo {
public static void main(String[] args) throws Exception{
String value = "ename:Smith|job:Clerk";
Emp emp = ClassInstanceFactory.create(Emp.class, value);
System.out.println("姓名:"+emp.getEname()+"、职位:"+emp.getJob());
}
}
运行结果: