Java泛型 - 将一个泛型转换为另一个泛型

时间:2016-06-14 19:56:00

标签: java generics

这是我的代码:

public class AnimationManager<STATE> {


private Map<STATE, Animation> animationMap = new HashMap<STATE, Animation>();


public void addAnimation(STATE state, BufferedImage[] frames, int frameDuration){
        animationMap.put(state, new Animation(frames, frameDuration));
}

public <E extends Enum<E>> void initAnimations(Player player, Constants.Heros chosen_hero, Class<E> heroStates){
        LinkedList<BufferedImage[]> frames = AssetsManager.getHeroGraphics(chosen_hero);

        assert frames != null;

        player.width = frames.get(0)[0].getWidth();
        player.height = frames.get(0)[0].getHeight();

        for(int i=0;i<frames.size();i++)
            addAnimation(heroStates.getEnumConstants()[i],frames.get(0),15);

}

}

在这一行:

addAnimation(heroStates.getEnumConstants()[i],frames.get(0),15);

编译器大喊:错误的第一个参数类型,找到&#39; E&#39;,必需&#39;状态&#39;

initAnimations()方法属于不同的类(没有STATE)时,它会编译并像魅力一样工作。他怎么可能不想获得第一个参数并将其转换为STATE类型呢?

1 个答案:

答案 0 :(得分:0)

类型参数STATE是无界的,可以使用任何类调用。类型参数E被限制为Enum的子类。变量heroStates是一个Class,这意味着getEnumConstants()方法返回一个E数组(这意味着Enum的某个子类的数组)。这不能安全地转换为STATE类型。

根据您的具体要求,有几种方法可以从这里开始。如果可以避免铸造,那将是更可取的。

如果你知道STATE类型参数总是一个枚举,你可以在STATE上设置一个绑定并完全跳过类型参数E:

class AnimationManager<STATE extends Enum<STATE>>
...
void initAnimations(Player player, Heros chosen_hero, Class<STATE> heroStates)

否则,如果您不知道STATE是枚举,那么您可以通过让initAnimations()方法的调用者提供它来避免获取枚举类型的类反射练习:

void initAnimations(Player player, Heros chosen_hero, List<STATE> heroStates)
...
addAnimation(heroStates.get(i), frames.get(0), 15);

并且调用类似于

AnimationManager<Foo> animationManager = ...;
animationManager.initAnimations(null, null, Arrays.asList(Foo.values()));

我真的不喜欢的第三种选择是施放。在这种情况下,您只需将有问题的行更改为

addAnimation((STATE)heroStates.getEnumConstants()[i], frames.get(0), 15);

这会为未经检查的广告系列生成警告,这意味着通用类型系统无法保证您在运行代码时不会以ClassCastException结束。

祝你好运!

相关问题