Skip to content

Instantly share code, notes, and snippets.

@kuoruan
Created July 9, 2018 09:50
Show Gist options
  • Save kuoruan/2039b02e8061c0c25b7241e5b2a1311f to your computer and use it in GitHub Desktop.
Save kuoruan/2039b02e8061c0c25b7241e5b2a1311f to your computer and use it in GitHub Desktop.
class BeanUtils {
public static <E, T> E covert(T src, Class<E> target) {
if (src == null) {
return null;
}
Method[] srcMethods = src.getClass().getMethods();
Method[] targetMethods = target.getMethods();
E targetObject = null;
try {
targetObject = target.newInstance();
for (Method m : srcMethods) {
String srcMethodName = m.getName();
if (srcMethodName.startsWith("get")) {
String targetMethodName = "set" + srcMethodName.substring(3);
for (Method mm : targetMethods) {
if (targetMethodName.equals(mm.getName()) &&
mm.getParameterTypes()[0].isAssignableFrom(m.getReturnType())) {
Object res = m.invoke(src);
mm.invoke(targetObject, res);
break;
}
}
}
}
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
logger.error("Covert Object failed ", e);
}
return targetObject;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment