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?

+1


source to share


4 answers


Create an interface like this

public interface Converter<S,T> {
  public T convert(S source);
}

      



and implement it for every X, Y, Z object. Then put all known converters in the map and have fun!

+6


source


While it doesn't work for edge cases, building a map between classes and converters

X.getClass () β†’ X Converter
Y.getClass () β†’ Y Converter



will help you get closer. You also want to check for superclasses if the sheet class is not found.

0


source


Code like this, with all its conditions instanceof

, screams for the interface!

You can create public interface Initializable

using the method public void initialize()

.

Then that's all, if your if-else will just resolve one call obj.initialize()

.

0


source


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.

0


source







All Articles