两个类相同属性名不同类型赋值
//将两个类同名属性 source的布尔值 设置到目标值的同名字符类别属性上 true->"1" false->"0"
public static void setSameNameField(Object source, Object target) throws InvocationTargetException, IllegalAccessException {
Field[] sourceFields = source.getClass().getDeclaredFields();
Field[] targetFields = target.getClass().getDeclaredFields();
Method mGet;
Method mSet;
outloop:
for (Field sourceField : sourceFields) {
try {
mGet = source.getClass().getMethod("get" + sourceField.getName().substring(0, 1).toUpperCase() + sourceField.getName().substring(1));
mSet = target.getClass().getDeclaredMethod("set" + sourceField.getName().substring(0, 1).toUpperCase() + sourceField.getName().substring(1), String.class);
}catch (NoSuchMethodException exception){
continue;
}
if (sourceField.getGenericType().getTypeName().equals("java.lang.Boolean")) {
for (Field targetField : targetFields) {
if (targetField.getName().equals(sourceField.getName()) && targetField.getGenericType().getTypeName().equals("java.lang.String")) {
if (mGet.invoke(source) != null && (Boolean) mGet.invoke(source)) {
mSet.invoke(target, "1");
continue outloop;
} else if (mGet.invoke(source) != null && (Boolean) mGet.invoke(source)) {
mSet.invoke(target, "0");
continue outloop;
}
}
}
}
}
}
其中 本版本java15
sourceField.getGenericType() 得到的是"class java.lang.String"之类;
sourceField.getGenericType().getTypeName()得到的是 "java.lang.String"之类;

浙公网安备 33010602011771号