Reputation: 2335
I have two sets of Java API's doing the same job but targeting different system platforms, all their API function definitions are exactly the same except that they have different package names (and they do not implement the same interface). I'm not free enough to change the code of the API, so I can not make them implement any interface.
I want to write code above these APIs and want to have these code to be usable for both API sets (similar to the strategy design pattern).
What is the best way to achieve this? I do not want to make a interface and adapter classes because there are over 20 API methods.
Upvotes: 2
Views: 456
Reputation: 9448
Despite being not what the original question wants, I would go with the Adapters for both APIs. Your Adapters would implement your own interface and could be used in a Strategy then.
This also gives you the option to come up with your own interface and descriptive names for the actions you need and completely abstract away the underlying APIs. Maybe you do not need all 20 methods?
Hints:
An alternative approach would be to use java.lang.reflect.Proxy
(as explained by Beryllium). The implementation of the proxy is straight forward but you need to create the interface up front by hand.
Upvotes: 5
Reputation: 12998
You could use a dynamic proxy (java.lang.reflect.InvocationHandler), but this requires additional classes/interfaces as well. A dynamic proxy in this scenario would just reduce the number of methods you have to implement/delegate from 20 to 1 at the cost of reflection.
It has already been commented by Keppil that there is no way to get this "for free" in standard Java, because the standard Java way is to use an interface (you are looking for Groovy's duck typing).
Upvotes: 2