java - 通用 <T extends A> 类使用静态字段而不是 T 的静态字段

标签 java class inheritance

这是我的情况

public abstract class Actions {

    public static Actions STAND;
    public static Actions ATTACK;
    public static Actions COLONIZE;
    public static Actions DEFEND;
    public static Actions TURN_CW;
    public static Actions TURN_CCW;
    public static Actions DIE;

    public abstract long[] getFramesDurations();
    public abstract int[] getBaseTiles();
}

public class SimpleActions extends Actions{

    public static Actions STAND = new SimpleActions( new long[]{120,120,120,120,120,120,120}, new int[]{0,1,2,3,4,5,6});
    public static Actions ATTACK = new SimpleActions( new long[]{120,120,120,120,120,120,120,120,120}, new int[]{7,8,9,10,11,12,13,14,15});
    public static Actions COLONIZE = new SimpleActions( new long[]{120,120,120,120,120,120,120}, new int[]{7,8,9,10,11,12,13,14,15});
    public static Actions DEFEND = new SimpleActions(new long[]{1}, new int[]{1});
    public static Actions TURN_CW = new SimpleActions( new long[]{1}, new int[]{1});
    public static Actions TURN_CCW = new SimpleActions( new long[]{1}, new int[]{1});
    public static Actions DIE = new SimpleActions( new long[]{1}, new int[]{1});

    private final long[] mActionFramesDurations;
    private final int[] mActionBaseTiles;

    SimpleActions(long[] pActionFramesDurations, int[] pActionBaseTiles) {
        mActionFramesDurations = pActionFramesDurations;
        mActionBaseTiles = pActionBaseTiles;
    }

    public long[] getFramesDurations()
    {
        return mActionFramesDurations;
    }

    public int[] getBaseTiles()
    {
        return mActionBaseTiles;
    }
}

public abstract class A<T extends Actions> {
    A() {
        doSomething(T.STAND);
    }

    protected void doSomething(Actions action) { use action somewhere}
}

public class B extends A<SimpleActions> {
    B() {
        super();
    }
}

当 A 的构造函数调用 doSomething 时,我总是得到 nullPointerException,因为 action 为 null..

由于 B 扩展了 A,我希望它使用 SimpleActions.STAND,而不是 Actions.STAND。

我做错了什么?我应该怎么做?

最佳答案

泛型的类型参数在运行时是未知的。换句话说,在运行时,A<Actions> 之间没有区别。和一个 A<SimpleActions> .因此 jvm 无法判断您想要 SimpleActions.STAND , 而不是 Actions.STAND .如果您需要在运行时知道类型参数,则需要将它们放在一个单独的变量中。

如果不清楚,请阅读“运行时类型删除”。

根据您的评论进行编辑 - 如果您只在构造函数中执行此逻辑,则可以使构造函数看起来像

A( Class<? extends Action> actionType ){
    if( SimpleActions.class.isAssignableFrom( actionType )){
        doSomething( SimpleActions.STAND );
    }
    else{
        doSomething( Actions.STAND );
    }
}

如果在构造函数之外需要相同的逻辑,那么创建一个类型为 Class<? extends Action> 的成员变量里面A存储 actionType .

关于java - 通用 <T extends A> 类使用静态字段而不是 T 的静态字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8936038/

相关文章:

java - 如何在Spring中使用注释动态 Autowiring bean?

c# - 州命名惯例

Java:重命名 .jar 中的文件

java - 在 Java 静态方法声明中使用当前类

asp.net-mvc - 使用 ASP.NET MVC 的 JsonResult 类返回多个对象

派生类中构造函数和析构函数的 C++ LNK2019 错误

java - 如何直接从 Git 生成 javadoc

c++:用户定义类型的 vector ?

c++ - 链接器错误 C++ vtable

java - 抽象类中的具体方法