java - 在初始化时设置通用参数 - 在子类中

标签 java generics

我是嗯,泛型新手,我在这里面临一个问题:

public class AnimationManager<STATE>{
    void loadAnimation(STATE state){
        //blahblah
    }
}

public class Unit{
    // AnimationManager<SomeType> animationManager; // I don't want this !!!
    AnimationManager animationManager; // i want it's type to be set in a subclass
}

public class MediumUnit extends Unit{
// nvm
}

public class FirstUnit extends MediumUnit{

    enum FirstUnitStates{
        S1, S2;
    }

    // i want to set it's type here, in subclasses (FirstUnit, SecondUnit etc.)
    public FirstUnit(){

        // this is ok, but It still doesn't have a type (it yells that I can remove the type from below statement)
        animationManager = new AnimationManager<FirstUnitStates>();

        // and now the problem - Unchecked call to loadAnimation(STATE) as a member of raw type.
        animationManager.loadAnimation(S1);
    }
}

如果没有类型转换或类似的东西,这可以实现我的目标吗?制作通配符,对象类型?

我想让每个单元(FirstUnit、SecondUnit)都可以在 AnimationManager 中设置自己的类型(将自己的状态存储在枚举中)。

编辑

我编辑了我的问题,因为我在 Unit 和 FirstUnit 之间多了一个类。 Nicolas Filotto 解决方案很完美,但它不适用于我的问题 - 我必须将参数从 FirstUnit 传递到 MediumUnit,再从 MediumUnit 传递到 Unit - 而且它根本不起作用。

最佳答案

你应该做的是:

public class Unit<T> {
    AnimationManager<T> animationManager;

...

public class FirstUnit extends Unit<FirstUnitStates> {

响应更新:

这与您需要简单参数化 MediumUnit 的想法相同,如下

public class Unit<T> {
    AnimationManager<T> animationManager;

...

public class MediumUnit<T> extends Unit<T> {

...

public class FirstUnit extends MediumUnit<FirstUnitStates> {

关于java - 在初始化时设置通用参数 - 在子类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37831796/

相关文章:

java - 使用 JTable 的默认列排序器对整数进行排序?

java - 如何在 fragment 中设置 UI 值

java - Tomcat 如何检测 JSP 页面并将其转换为 Servlet?

java - 我可以让编译器忽略绑定(bind)不匹配错误吗? (或者修复它的这个实例)

Java 泛型和反射

java - 为什么隐式类型推断只能在赋值中起作用?

java - Java 泛型绑定(bind)中的原始类型

java - XML解析: Cannot Find Nodes by Tagname

java - 如何防止用户在java中的spring REST API中的整数字段中输入小数值

java - Java 中的 "both arguments must have the same type"怎么说?