rakesh99
rakesh99

Reputation: 1266

Java generic utility method to convert between two types

I have a method to convert between objects of two different classes. These are DTO objects and hibernate entity classes.

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;
      }

Instead of having same method with DomainObject2 and PersistedObject2 and so on .. Is it possible to have a generic method with below signature? (without having to pass source and target class)

 public static<U,V> U convertToDomain(V pObj) {
    ...}

PS: (A different topic that it is wasteful to use DTO when entities have same structure which some people don't agree to despite hibernate documentation and other sources)

Upvotes: 3

Views: 1978

Answers (1)

bashar
bashar

Reputation: 415

To achieve this you would need to pass the class of the Domain object you are looking for. Something like the following would work:

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;
}

With that being said, as it appears, you are already using Spring. You could try registering a special converter with Spring'sConversionService (Auto wire conversion service) and you can use the convert method to achieve the same result).

Please note that you should add some checks to make sure that each the entity and the domain objects are compatible otherwise you'd end up with a big mess and your code would be error prone.

Upvotes: 1

Related Questions