- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我认为我的设置有点不传统,所以解释会更长一些。我有一个抽象父类(super class),其方法为
public abstract T execute(P parameters);
我有一组扩展它的实现类,并在扩展语句中分配单独的类型。这意味着该实现不是通用的。
我通过注释@Example获取所有实现。我使用 ClassGraph 来提取有关这些类的信息。通过它,我不仅获得了实现,还获得了具有已定义类型的正确父类(super class)。
但是我现在无法使用 Guice bind().to();
提供更多背景信息...
我有一组实现类,它们与外部 API 进行通信。每个类(class)都与一个单独的区域进行通信。我希望我自己的服务 API 不依赖于特定的实现。我看不到 future ,而且很有可能我们需要稍后更灵活地绑定(bind)实现(例如,同一调用有 3 种不同的实现)。外部服务具有高度的灵 active ,因此消费者也必须具有类似的灵 active 。
因此,我的目标是使用 guice 带注释的绑定(bind)
bind(super.class).annotatedWith(Names.named(path)).to(implementation.class);
另一方面,在我自己的服务 API 中,我希望使用 @Named 注释进行用户方法注入(inject)来定义绑定(bind)接收。
@Inject
public void setImplementation(@Named(path) Super<InputType, OutputType> implementation){...}
上述方法的问题是通用的 . super.class 绑定(bind)不考虑这些,因此未找到任何绑定(bind)。
我接下来在 Guice 中使用 TypeLiteral 阅读了通用绑定(bind)。然而我没有找到一种让编译器满意的方法。
我从 ClassGraph 收到 ClassInfo。所以我尝试了以下设置
//class list is the result of ClassGraph
for (Class<?> entry : classList){
Class<? extends Super> implementationClass = (Class<? extends Super> entry;
String value = entry.getAnnotation(Example.class).value();
TypeLiteral<? extends Super> typeLiteral = TypeLiteral.get(implementationClass);
TypeLiteral<?> supertype = typeLiteral.getSupertype(Super.class);
//now the trials start and all are wrong, annotation is left out for now
bind(impelmentationClass.getSuperclass()).to(implementationClass);
bind(impelmentationClass.getSuperclass()).to(entry);
bind(impelmentationClass.getSuperclass()).to(typeLiteral);
bind(supertype).to(implementationClass);
bind(supertype).to(entry);
bind(supertype).to(typeLiteral);
}
我正在尝试的是不可能的,还是我使用 TypeLiteral 错误?我确实搜索了两天并尝试了更多不同的方法(这只是离家最近的方法)。所以我有点陷入僵局,我希望其他人以前也遇到过这个问题:)
感谢任何帮助
最佳答案
我刚刚尝试了一下(可能不完全相同),但这似乎在我的环境中有效:
public abstract class ChequePrinter<T> implements Printer<T, PrintLayout> {
public abstract print(T cheque);
}
public VoidChequePrinter extends ChequePrinter<VoidCheque> {
public print (VoidCheque cheque);
}
非常简单,除了我打印到 PrintLayout 而不是网络请求,但这并不重要。现在,对于我的示例,我只是硬编码了类定义,而不是从 ClassGraph 中提取它们,但只要:
Class<?> entry is a regular class
应该没问题。这是我刚刚使用的:
// should be the same as entry
Class<? extends ChequePrinter<?>> clazz = VoidChequePrinter.class;
TypeLiteral typeLiteral = TypeLiteral.get(clazz.getGenericSuperClass());
bind(typeLiteral).annotatedWith(Names.named("Void")).to(clazz);
在我的测试类VoidChequePrinterTest
中,我有:
@Inject @Named("Void") ChequePrinter<VoidCheque> printer;
正如我所期望的那样,得到了正确的结果。
关于java - 将泛型抽象父类(super class)绑定(bind)到多个非泛型实现类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58604098/
我是一名优秀的程序员,十分优秀!