Java generic utility for converting between two types

I have a method for converting between objects of two different classes. These are DTOs and hibernation 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;
      }

      

Rather than have the same method DomainObject2

, and PersistedObject2

etc. Is it possible to have a generic method with a signature? (no need to pass in source and target class)

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

      

PS: (A different topic that it is wasteful to use DTOs when objects have the same structure, which some people disagree despite hibernate documentation and other sources)

+3


source to share


1 answer


To do this, you need to pass the class of the Domain object you are looking for. The following will 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 said, as it turns out, you are already using Spring. You can try to register a custom converter with Spring 's ConversionService

(automatic channel conversion service) and you can use the method convert

to achieve the same result).

Note that you must add some checks to ensure that every object and domain object is compatible, otherwise you will have a lot of mess and your code will be error prone.

+1


source







All Articles