newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h);
返回指定接口(interface)的代理类实例,该接口(interface)将方法调用分派(dispatch)给指定的调用处理程序。
我需要封装此方法返回的实例(例如,封装到其他类中),这样它也将扩展其他类。所以最后一个类将扩展一个类并实现指定的接口(interface)。
要扩展的类是:
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 实现的所有接口(interface)的类实例。
最佳答案
你不能这样做,因为从 newProxyInstance
返回的对象已经继承自其他一些类,而你不能从 Java 中的两个类继承。
您需要将oref
保留为实现InvocationHandler
接口(interface)的类的实例变量。您将在 InvocationHandler
的构造函数中初始化 oref
,并通过以下方法提供访问 oref
的接口(interface):
public interface IProxy {
ObjectRef getOref();
}
您的 InvocationHandler
应该通过返回其 oref
成员来响应 getOref
的调用。
关于java - 如何使 java.lang.reflect.Proxy.newProxyInstance() 返回的对象扩展其他类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8450324/