我有一个内部类,用于存储我在游戏中使用的控件的信息,现在我想在其中存储一个静态 ArrayList,其中包含所有控件的名称。但是我收到了这个错误:“Modifier static is only allowed in constant variable declarations”
private class Control{
public static ArrayList<String> keys = new ArrayList<String>();
public final String key;
public final Trigger trigger;
Control(String k, Trigger t){
key = k;
trigger = t;
keys.add(key);
}
}
现在我知道这可以通过将 ArrayList 从类中取出并将其存储在主类中来轻松解决。但我更愿意将所有信息保存在一个可以访问所有内容的类中。
“Control.key、Control.trigger、Control.keys” 只是比更优雅/更易读 “键、触发器、键”
或者也许我只是患有强制症,但我还是想按照自己的方式去做。
最佳答案
您可以将 Control
类设为静态。
private static class Control {
^^^^^^
// Ok to have static members:
public static ArrayList<String> keys = new ArrayList<String>();
...
这在 Java 语言规范 Section §8.1.3 中有描述。
8.1.3 Inner Classes and Enclosing Instances
An inner class is a nested class that is not explicitly or implicitly declared static. Inner classes may not declare static initializers (§8.7) or member interfaces. Inner classes may not declare static members, unless they are compile-time constant fields (§15.28).
关于java - 修饰符 static 只允许在常量变量声明中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6440010/