属性复制和转换
作者:互联网
属性复制和转换
public static <X> X toBean(Object src, Class<X> t) {
if (t == null) {
return null;
}
X instance = null;
try {
instance = t.newInstance();
if (src != null) {
copyProperties(src, instance);
}
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return instance;
}
public static void copyProperties(Object src, Object dist) {
if (src == null || dist == null) {
return;
}
Field[] srcFields = src.getClass().getDeclaredFields();
Field[] distFields = dist.getClass().getDeclaredFields();
for (Field field : srcFields) {
if ("serialVersionUID".equals(field.getName())) {
continue;
}
try {
field.setAccessible(true);
Object o = field.get(src);
if (o == null) {
continue;
}
for (Field distField : distFields) {
if (field.getName().equalsIgnoreCase(distField.getName())) {
distField.setAccessible(true);
distField.set(dist, o);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
标签:src,转换,Field,field,复制,dist,null,distField,属性 来源: https://www.cnblogs.com/muphy/p/16611658.html