使用JAVA反应进行两个vo有相同字段名字进行子转换:
@Test
public void doTransTest() {
A a= new A();
A.setC(111L);
B b= new B();
doTrans(a, b);
}
public void doTrans(Object sour, Object dest) {
if (sour == null) {
dest = null;
return;
}
//反射原理应用
Class> sourceClass = sour.getClass();
Class> destClass = dest.getClass();
for (Field field : sourceClass.getDeclaredFields()) {
String fieldName = field.getName();
Object value;
if (fieldName.equals("serialVersionUID")) {
continue;
}
try {
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(fieldName, sourceClass);
value = propertyDescriptor.getReadMethod().invoke(sour);
} catch (Exception e) {
//log
continue;
}
if (value == null) {
continue;
}
try {
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(fieldName, destClass);
propertyDescriptor.getWriteMethod().invoke(dest, value);
} catch (Exception e) {
//log
continue;
}
}
}
SpringIOC反射的应用:
@Test
public void reflexTest() throws Exception {
//解析bean字符串xxxxx
String beanId = "cartBean";
String beanClass = "com.mmall.pojo.Cart";
Class> cls = Class.forName(beanClass);
Object object = cls.newInstance();
//模拟spring容器
Map container = Maps.newHashMap();
//bean注入spring容器,实例化成功
container.put(beanId, object);
//初始化refBean(userBean)
String beanIdUser = "cartBean";
String beanClassUser = "com.mmall.pojo.User";
Class> clsUser = Class.forName(beanClassUser);
Object objectUser = clsUser.newInstance();
//并注入spring容器
container.put(beanIdUser,objectUser);
//得到cartBean的setUser方法
String setUserName = "setUser";
Object paramBean = container.get(beanIdUser);
//cls是cart对象
Method setter = cls.getMethod(setUserName, objectUser.getClass());
//注入set方法
setter.invoke(object, paramBean);
}