Java guice工厂中的泛型返回类型存在问题
到目前为止,我成功地使用了GoogleGuice2。在迁移到guice 3.0时,我遇到了与辅助注射工厂有关的问题。假设以下代码Java guice工厂中的泛型返回类型存在问题,java,guice,guice-3,Java,Guice,Guice 3,到目前为止,我成功地使用了GoogleGuice2。在迁移到guice 3.0时,我遇到了与辅助注射工厂有关的问题。假设以下代码 public interface Currency {} public class SwissFrancs implements Currency {} public interface Payment<T extends Currency> {} public class RealPayment implements Payment<SwissF
public interface Currency {}
public class SwissFrancs implements Currency {}
public interface Payment<T extends Currency> {}
public class RealPayment implements Payment<SwissFrancs> {
@Inject
RealPayment(@Assisted Date date) {}
}
public interface PaymentFactory {
Payment<Currency> create(Date date);
}
public SwissFrancPaymentModule extends AbstractModule {
protected void configure() {
install(new FactoryModuleBuilder()
.implement(Payment.class, RealPayment.class)
.build(PaymentFactory.class));
}
}
到目前为止,我找到的唯一解决方法是从factory方法的返回类型中删除泛型参数:
public interface PaymentFactory {
Payment create(Date date);
}
有人知道为什么guice 3不喜欢工厂方法中的泛型参数,或者我对工厂的误解吗?谢谢 上面的代码有两个问题
首先,
RealPayment
实现Payment
,但是PaymentFactory.create
返回Payment
。无法从返回付款的方法返回付款。如果您将create
的返回类型更改为Payment,我想知道您是否应该将TypeLiteral
而不是Payment.class
传递到implement
中?@Jeremy Heiler谢谢,但您会怎么做TypeLiteral
没有公共构造函数,如果使用TypeLiteral.get(Payment.class)
,则会出现相同的异常。可能是这样?TypeLiteral.get(Types.newParameterizedType(Payment.class,Currency.class))代码>一般的TypeLiteral
应该像这样创建:newtypeliteral(){}
。注意{}
。。。必须创建一个子类才能获得完整的通用信息。@Jeremy Heiler:不,那不行。将建议的TypeLiteral
与implement
方法一起使用时,存在类型不匹配。
bind(PaymentFactory.class).toProvider(
FactoryProvider.newFactory(PaymentFactory.class, RealPayment.class));
public interface PaymentFactory {
Payment create(Date date);
}
new TypeLiteral<Payment<? extends Currency>>() {}