Simple / elegant way to convert object to object in Java?
I need to take and improve / finish some code that converts Java objects from third party library to internal objects. This is currently done with a large if-else statement in lines:
if (obj instanceOf X)
{
//code to initialize internal object
}
else if (obj instanceOf Y)
{
//code to initialize different object
}
else if (obj instanceOf Z)
{
//more init code
}
...
Personally, I don't find this solution satisfactory; it's long and messy, and to make matters worse, many if-else blocks contain more if-else blocks related to subclasses and edges. Is there a better solution to this problem?
source to share
If these internal objects represent the interface to the application and are not used directly, adapt them rather than convert them.
That is, if you have something like this:
public class ThirdPartyClass { ... }
public interface InternalInterface { ... }
public class InternalClass { ... }
Internal foo(ThirdPartyClass thirdParty) {
InternalClass internal = new InternalClass();
// convert thirdPaty -> internal
return internal;
}
Then do something like this instead:
public class ThirdPartyClass { ... }
public interface InternalInterface { ... }
public class InternalClass { ... }
public class ThirdPartyInternalAdapter implements InternalInterface {
private final ThirdPartyClass thirdParty;
public ThirdPartyInternalAdapter(ThirdPartyClass thirdParty) {
this.thirdParty = thirdParty;
}
// implement interface in terms of thirdParty
}
It's not clear from your question if this applies, but if it does, it might be easier and more efficient than converting an object to an object directly.
source to share