在两种类型之间转换的Java通用实用程序方法
我有一个方法可以在两个不同类的对象之间进行转换。 这些是DTO对象和hibernate实体类在两种类型之间转换的Java通用实用程序方法,java,spring,generics,Java,Spring,Generics,我有一个方法可以在两个不同类的对象之间进行转换。 这些是DTO对象和hibernate实体类 public static DomainObject1 convertToDomain(PersistedObject1 pObj) { if (pObj == null) return null; DomainObject1 dObj = new DomainObject1(); BeanUtils.copyProperties(pO
public static DomainObject1 convertToDomain(PersistedObject1 pObj) {
if (pObj == null)
return null;
DomainObject1 dObj = new DomainObject1();
BeanUtils.copyProperties(pObj,dObj); //Copy the property values of the given source bean into the target bean.
return dObj;
}
而不是使用与DomainObject2
和PersistedObject2
等相同的方法是否可以有一个具有以下签名的泛型方法?(无需传递源类和目标类)
公共静态U转换器域(V pObj){
...}
PS:(尽管有hibernate文档和其他来源,但当实体具有某些人不同意的相同结构时,使用DTO是浪费的)要实现这一点,您需要传递您正在寻找的域对象的类。类似于以下内容的操作将起作用:
public static <T> T convert(Object source, Class<T> targetType)
throws InstantiationException,
IllegalAccessException,
InvocationTargetException {
if (source == null)
return null;
T target = targetType.newInstance();
BeanUtils.copyProperties(source, target);
return target;
}
publicstatict转换(对象源,类targetType)
抛出实例化异常,
非法访问例外,
调用目标异常{
if(source==null)
返回null;
T target=targetType.newInstance();
copyProperties(源、目标);
回报目标;
}
话虽如此,您似乎已经在使用Spring了。您可以尝试使用Spring的ConversionService
(自动导线转换服务)注册一个特殊的转换器,您可以使用conversion
方法获得相同的结果)
请注意,您应该添加一些检查,以确保每个实体和域对象都是兼容的,否则最终会导致混乱,代码容易出错。如果您使用的是Apache Commons,我认为应该是:BeanUtils.copyProperties(目标、源)(可能对Spring是正确的…)
public static <T> T convert(Object source, Class<T> targetType)
throws InstantiationException,
IllegalAccessException,
InvocationTargetException {
if (source == null)
return null;
T target = targetType.newInstance();
BeanUtils.copyProperties(source, target);
return target;
}