Guice,扩展接口和构造函数返回类型

时间:2012-12-02 21:08:56

标签: java casting dependency-injection guice

接口A及其实现:

public interface A<K, E> {
    public void foo();
}

public abstract class AImpl<K, E> implements A<K, E> {
    public void foo(){};
}

接口B,它扩展了接口A及其实现:

public interface B extends A<Integer, String> {
    public void bar();
}

public class BImpl extends AImpl<Integer, String> implements B {
    public void bar(){};
}

抽象类C,它被A注入:

public abstract class C<K, E> {
    A<K, E> a;

   @Inject
   public setA(A<K, E> a){
       this.a = a;
   }

   public A<K, E> getA(){
       return a;
   }
}

Guice:

bind(new TypeLiteral<A<Integer, Book>>(){}).to(BImpl.class);

最后一个类,它扩展了C类:

public class D extends C<Integer, String> {
   public void fooBar(){
        this.getA().bar(); //Gets BImpl injected by Guice, and call bar():  Not working - error
        ((B) this.getA()).bar(); //Working
   }
}

从内联注释中可以看出,BImpl可以正确注入,如果没有其他方法,可以使用,扩展A(接口B为空)。如果我在B中添加任何新方法,我不能在没有它转换为B的情况下在D中调用它。我的主要目标是,为用户提供扩展A并在D中使用此功能的可能性。

1 个答案:

答案 0 :(得分:3)

  

如果我在B中添加任何新方法,我不能在没有它转换为B的情况下在D中调用它。我的主要目标是,让用户可以扩展A并在D中使用此功能。

如果用户需要B但不是A提供的功能,则应声明他们需要 B。类D应该声明它需要什么 - 不依赖于强制转换来确保它被正确配置超出声明的范围。