0

假设我有以下基类,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;
    }
}
4

1 回答 1

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);
于 2012-07-26T10:46:19.590 回答