Created
July 9, 2018 09:50
-
-
Save kuoruan/2039b02e8061c0c25b7241e5b2a1311f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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