Any risk using a single dollar sign `$` as a java class name?

前端 未结 5 1109
渐次进展
渐次进展 2020-12-18 20:27

Originally I was using the underscore _ as a class name. The new Java8 compiler complains that it \"might not be supported after Java SE 8\". I changed

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-18 20:55

    Huh, you're right, using a $ in a classname works. Eclipse complains that it is against convention, but, if you are sure, you can do it.

    The problem (conventionally) with using a $ is that the $ is used in the class hierarchy to indicate nested classes.... for example, the file A.java containing:

    class A {
       class SubA {
       }
    }
    

    would get compiled to two files:

    1. A.class
    2. A$SubA.class

    Which is why, even though $ works, it is ill advised because parsing the jars may be more difficult... and you run the risk of colliding two classes and causing other issues

    EDIT, I have just done a test with the following two Java files (in the default package)

    public class A {
        private static final class SubA {
            public String toString() {
                return "I am initializing Nested SUBA";
            }
        }
    
        private static final SubA sub = new SubA();
        public A() {
            System.out.println("What is " + sub.toString());
        }
    }
    
    
    
    public class A$SubA {
        @Override
        public String toString() {
            return "I am A$SubA";
        }
    }
    
    
    public class MyMain {
        public static void main(String[] args) {
            System.out.println(new A());
            System.out.println(new A$SubA());
        }
    }
    

    And the code will not compile.....

    Two problems, type A$SubA is already defined, and can't reference a nested class A$SubA by it's binary name.

提交回复
热议问题