Java 工具类
将一个类中的值通过setter和getter传递给另一个类型
public static <T> T entityToDto(Object entity, Class<T> dtoType) {
T instance;
try {
instance = dtoType.getDeclaredConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new RuntimeException(e);
}
// 反射entity 获取getter
Class<?> entryType = entity.getClass();
Arrays.stream(dtoType.getMethods()).filter(
method -> method.getName().startsWith("set")
).forEach(method -> {
String methodName = method.getName().replace("set", "get");
try {
Object value = entryType.getMethod(methodName).invoke(entity);
method.invoke(instance, value);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignore) {}
});
return instance;
}
- 感谢你赐予我前进的力量
赞赏者名单
因为你们的支持让我意识到写文章的价值🙏
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 Salted Fish
评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果