2

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.

4

2 回答 2

5

尽管不是最初的问题想要的,但我会为这两个 API 使用适配器。您的适配器将实现您自己的接口,然后可以在策略中使用。

这也使您可以选择为您需要的操作提供自己的界面和描述性名称,并完全抽象出底层 API。也许您不需要全部 20 种方法?

提示:

  • 在 Eclipse 中,Source 菜单中有生成委托方法的功能,一旦您拥有要委托的类型的字段,就会为您创建 20 种委托方法。
  • 要提取接口,您可以使用创建和实现接口的函数 Refactor/ extract interface。

另一种方法是使用java.lang.reflect.Proxy(如 Beryllium 所解释的)。代理的实现很简单,但您需要预先手动创建接口。

于 2013-05-26T10:31:18.183 回答
2

您可以使用动态代理 (java.lang.reflect.InvocationHandler),但这也需要额外的类/接口。在这种情况下,动态代理只会以反射为代价将您必须实现/委托的方法数量从 20 个减少到 1 个。

Keppil 已经评论说,在标准 Java 中没有办法“免费”获得这个,因为标准 Java 方式是使用接口(您正在寻找 Groovy 的鸭子类型)。

于 2013-05-26T11:58:12.970 回答