spring - Java generic utility method to convert between two types -


i have method convert between objects of 2 different classes. these dto objects , hibernate entity classes.

public static domainobject1 converttodomain(persistedobject1 pobj) {         if (pobj == null)           return null;         domainobject1 dobj = new domainobject1();         beanutils.copyproperties(pobj,dobj); //copy property values of given source bean target bean.         return dobj;       } 

instead of having same method domainobject2 , persistedobject2 , on .. is possible have generic method below signature? (without having pass source , target class)

 public static<u,v> u converttodomain(v pobj) {     ...} 

ps: (a different topic wasteful use dto when entities have same structure people don't agree despite hibernate documentation , other sources)

to achieve need pass class of domain object looking for. following 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 being said, appears, using spring. try registering special converter spring'sconversionservice (auto wire conversion service) , can use convert method achieve same result).

please note should add checks make sure each entity , domain objects compatible otherwise you'd end big mess , code error prone.


Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -