如何使 java.lang.reflect.Proxy.newProxyInstance() 返回的对象扩展其他类
newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h);
返回指定接口的代理类实例,该接口将方法调用分派到指定的调用处理程序。
我需要封装此方法返回的实例(例如,封装到其他类中),以便它也可以扩展其他类。所以最终的类将扩展一个类并实现指定的接口。
要扩展的类是:
public class IProxy {
ObjectRef oref;
public IProxy(ObjectRef oref) {
this.oref = oref;
}
}
所以过程应该是:
MyInterface() mi=(MyInterface) newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h);
// some magic trick
最后我想要一个扩展 IProxy 并实现 mi 实现的所有接口的类的实例。
newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h);
Returns an instance of a proxy class for the specified interfaces that dispatches method invocations to the specified invocation handler.
I need to encapsulate instance returned by this method (for example,into some other class) so, that it will also extend other class. So the final class will extend one class and implement specified interfaces.
class to extend is:
public class IProxy {
ObjectRef oref;
public IProxy(ObjectRef oref) {
this.oref = oref;
}
}
so the process should be :
MyInterface() mi=(MyInterface) newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h);
// some magic trick
and in the end I would like to have instance of class that extends IProxy and implements all interfaces that mi did implement.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不能这样做,因为从
newProxyInstance
返回的对象已经继承自其他一些类,并且你不能从 Java 中的两个类继承。您需要将
oref
保留为实现InvocationHandler
接口的类的实例变量。您将在InvocalHandler
的构造函数中初始化oref
,并提供一个接口来通过方法访问oref
:您的
InitationHandler 应该通过返回其
oref
成员来响应getOref
的调用。You cannot do it, because the object returned from
newProxyInstance
already inherits from some other class, and you cannot inherit from two classes in Java.You need to keep
oref
as an instance variable of your class that implements theInvocationHandler
interface. You will initializeoref
in the constructor of theInvocationHandler
, and provide an interface to accessoref
through a method:Your
InvocationHandler
should respond to calls ofgetOref
by returning itsoref
member.