事后实现接口 [英] implementing interfaces after the fact

查看:115
本文介绍了事后实现接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为,Java中无法完成以下操作。但是我很乐意学习如何实现与之类似的东西。



假设我们有一个已经在编译代码中使用的C类。 (我们既不能改变代码也不能改变C的原始定义)



假设有更多有趣的代码可以被重用,如果只有C将实现接口I实际上,它实际上或多或少是导出D只是C ++实现接口方法。



然而,似乎没有办法,一旦我有一个C,说:我要你成为一个D,那就是C实现我。



(旁注:我认为演员)c,其中c的运行时类型为C,如果D为C,则应该允许C和C的唯一区别是添加方法,这应该是安全的,应该不是吗?)



如何解决这个灾难?



(我知道工厂设计模式,但这不是一个解决方案,似乎,一旦我们管理在以前是C的所有地方创建D,有人发现另一个接口J有用,并导出E扩展C实现J.但是E和D是不兼容的,因为它们都添加了一个diffe租一套方法C.所以当我们可以总是通过一个预期的C的E,我们不能通过一个预期的D的E。相反,现在,我们需要一个新的类F扩展C实现I,J。)

解决方案

要兼容是接口,那么没有问题,请查看动态代理类,它基本上如何在java中在运行时实现接口。



如果您需要与类类似的运行时兼容性,我建议您采取看看cglib或javaassist的开源库。


I think, the following can't be done in Java. But I would be happy to learn how to implement something that resembles it.

Suppose we have a class C, that is already used in compiled code. (We can neither change that code nor the original definition of C).

Suppose further there is interesting code that could be re-used, if only C would implement interface I. It is, in fact, more or less trivial to derive D that is just C + the implementation of the interface methods.

Yet, it seems there is no way, once I have a C, to say: I want you to be a D, that is, a C implementing I.

(Side remark: I think the cast (D)c, where c's runtime type is C, should be allowed if D is a C and the only difference to C are added methods. This should be safe, should it not?)

How could one work around this calamity?

(I know of the factory design pattern, but this is not a solution, it seems. For, once we manage to create D's in all places where formerly were C's, somebody else finds another interface J useful and derives E extends C implements J. But E and D are incompatible, since they both add a different set of methods to C. So while we can always pass an E where a C is expected, we can't pass an E where a D is expected. Rather, now, we'd need a new class F extends C implements I,J.)

解决方案

If all that you need to be compatible with is interfaces then no problem take a look at dynamic proxy classes, its basically how you implement interfaces at runtime in java.

if you need similar runtime compatibility with classes I suggest you take a look at cglib or javaassist opensource libraries.

这篇关于事后实现接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆