假设我有以下基类,Queen和Knight作为其衍生物。 WeaponBehaviour是一个界面。根据具体的GameCharacter类型,我无法弄清楚如何使用Guice注入武器。
public abstract class GameCharacter {
@Inject
protected WeaponBehaviour weapon;
public GameCharacter() {
}
public void fight() {
weapon.useWeapon();
}
public void setWeapon(WeaponBehaviour weapon) {
this.weapon = weapon;
}
}
答案 0 :(得分:6)
您可以使用Binding Annotations。
子类:
class GimliSonOfGloin extends GameCharacter {
@Inject
public void setWeapon(@Axe WeaponBehaviour weapon) {
super.setWeapon(weapon);
}
}
注释:
@BindingAnnotation
@Target({ FIELD, PARAMETER, METHOD })
@Retention(RUNTIME)
public @interface Axe {}
绑定:
bind(WeaponBehaviour.class)
.annotatedWith(Axe.class)
.to(MyAxe.class);