@Blankj 用反射可以实现,我这边项目中只是实现了基本代码,很多情况没有考虑。通过属性的get,set方法调用,这里有个基本类可以参考下:
private static void copyPropertiesExclude(Object from, Object to) throws Exception {
Method[] fromMethods = from.getClass().getDeclaredMethods();
Method[] toMethods = to.getClass().getDeclaredMethods();
Method fromMethod, toMethod;
String fromMethodName, toMethodName;
for (Method fromMethod1 : fromMethods) {
fromMethod = fromMethod1;
fromMethodName = fromMethod.getName();
boolean isStartMethod = fromMethodName.startsWith("is");
if (!(fromMethodName.startsWith("get") || isStartMethod) || fromMethodName.contains("getId"))
continue;
toMethodName = "set" + fromMethodName.substring(isStartMethod ? 2 : 3);
toMethod = findMethodByName(toMethods, toMethodName);
if (toMethod == null)
continue;
Object value = fromMethod.invoke(from);
if (value == null)
continue;
if (value instanceof Collection) {
Collection newValue = (Collection) value;
if (newValue.size() <= 0)
continue;
}
toMethod.invoke(to, value);
}
}