Error: field name cannot be declared static

2019-02-22 08:44发布

问题:

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();
    }
}

Compilation Error: The field name cannot be declared static in a non-static inner type, unless initialized with a constant expression

Solution to this?

回答1:

Java does not let you define non-final static fields inside function-local inner classes. Only top-level classes and static nested classes are allowed to have non-final static fields.

If you want a static field in your Constants class, put it at the Application class level, like this:

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();
    }
}


回答2:

From the JLS section 8.1.3:

Inner classes may not declare static members, unless they are constant variables (§4.12.4), or a compile-time error occurs.

So you're fine if you just make the variable 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();
    }
}

Of course this won't work if you need to initialize it with a non-constant value.

Having said all of this, it's an unusual design, IMO. It's very rare to see a named local class at all, in my experience. Do you need this to be a local class? What are you trying to achieve?