错误:字段名称不能声明为static

P R*_*ant 5 java static multithreading inner-classes

public class Application {
    public static void main(String[] args) {
        final class Constants {
            public static String name = "globe";
        }
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Constants.name);
            }
        });
        thread.start();
    }
}
Run Code Online (Sandbox Code Playgroud)

编译错误: The field name cannot be declared static in a non-static inner type, unless initialized with a constant expression

解决这个问题?

das*_*ght 8

Java不允许您在函数本地内部类中定义非最终静态字段.只允许顶级类和静态嵌套类具有非最终静态字段.

如果你想static在你的Constants班级中使用某个字段,请将其放在Application类级别,如下所示:

public class Application {
    static final class Constants {
        public static String name = "globe";
    }
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Constants.name);
            }
        });
        thread.start();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 你的第一句话是不正确的 - 如果该字段在原始代码中成为`final`它将编译,因为它是用常量值初始化的. (2认同)

Jon*_*eet 6

JLS第8.1.3节:

内部类可能不会声明静态成员,除非它们是常量变量(第4.12.4节),否则会发生编译时错误.

如果您只是变量,那么你很好final:

public class Application {
    public static void main(String[] args) {
        final class Constants {
            public static final String name = "globe";
        }
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Constants.name);
            }
        });
        thread.start();
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,如果需要使用非常量值初始化它,这将不起作用.

说完所有这些,这是一个不寻常的设计,IMO.根据我的经验,很难看到一个命名的本地课程.你需要这个本地课吗?你想要实现什么目标?