你能强制一个java对象在运行时实现一个接口吗?
现在我的以下内容:
1)java接口。
2)具体的java 不的类实现上述接口,但确实包含与接口中定义的每个方法匹配的方法签名。
2) A concrete java class that does not implement the aforementioned interface, but does contain a method signature matching every one of the methods defined in the interface.
由于我无法更改第2项的实现,因此我想知道是否可以创建一个方法来接受第1项的实例作为参数接受第2项而没有类强制转换异常。
Since I am unable to change the implementation of item 2, I would like to know if it is possible to make a method that accepts an instance of item 1 as an argument accept item 2 without a class cast exception.
感觉就像Spring中的各种编织/强制/ AOP机制应该使这成为可能,但我不知道该怎么做。
It feels like the various weaving/coercion/AOP mechanics in Spring should make this possible, but I don't know how to do it.
有没有办法让这种情况发生?
Is there a way to make this happen?
可以你强制一个java对象在运行时实现一个接口?
Can you force a java object into implementing an interface at runtime?
是的,使用动态代理或字节 - 代码重写。但是,对我而言,您似乎正在寻找 适配器模式
。
Yes, using dynamic proxies or byte-code rewriting. However, to me it seems like you're looking for the Adapter pattern
.