你能强制一个java对象在运行时实现一个接口吗? [英] Can you force a java object into implementing an interface at runtime?

查看:192
本文介绍了你能强制一个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.

这篇关于你能强制一个java对象在运行时实现一个接口吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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