我有一个接口(interface)类引用和一个使用实现上述接口(interface)的动态代理创建的对象。
final Class<?> interfaceType;
final Object interfaceImplementation = Proxy.newProxyInstance(...)`
我想通过将接口(interface)绑定(bind)到代理对象来使代理实例在 Guice 应用程序上下文中可用。我尝试过,但未能通过 Guice 快速实现这一目标。
是否可以执行以下操作:
bind(interfaceType).toInstance(interfaceImplementation);
这样我就可以将接口(interface)注入(inject)到其他类中?
最佳答案
问题在于 Proxy.newProxyInstance()
的返回类型只是 Object
,但是bind(...).toInstance(...)
想要确保类型与 ?
相同来自Class<?> interfaceType
。在某些时候,您将需要进行未经检查的转换才能使一切正常运行。我的写法如下:
private <T> T newProxyInstance(ClassLoader loader, InvocationHandler handler, Class<T> primaryInterface, Class<?>... extraInterfaces) {
Class<?>[] allInterfaces = Lists.asList(primaryInterface, extraInterfaces)
.stream()
.toArray(Class<?>[]::new);
@SuppressWarning("unchecked")
T proxy = (T) Proxy.newProxyInstance(loader, allInterfaces, handler);
return proxy;
}
那我想
bind(interfaceType)
.toInstance(newProxyInstance(loader, handler, interfaceType[, ...]));
可以。
关于java - 使用 Guice 将接口(interface)绑定(bind)到实现它的代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41752770/