Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

Java class name containing dollar sign fails to compile if an inner class is present

I've got following Java classes defined:

mac-grek:javajunk grek$ cat A$B.java
class A$B {}
mac-grek:javajunk grek$ cat A.java
public class A {
  public static class B {}
}
mac-grek:javajunk grek$ cat Main.java 
public class Main {

  public static void main(String[] args) {
    System.out.println(A.B.class.getName());
    System.out.println(A$B.class.getName());
  }

}

When I try to compile them, I get following errors:

mac-grek:javajunk grek$ javac 'A$B.java' A.java Main.java
A.java:2: duplicate class: A.B
  public static class B {}
                ^
Main.java:4: cannot find symbol
symbol  : class B
location: class A
    System.out.println(A.B.class.getName());
                        ^
Main.java:5: cannot find symbol
symbol  : class A$B
location: class Main
    System.out.println(A$B.class.getName());
                       ^
3 errors

If I remove A.java file and System.out.println(A.B.class.getName()); from Main.java everything compiles:

mac-grek:javajunk grek$ cat A$B.java 
class A$B {}
mac-grek:javajunk grek$ cat Main.java 
public class Main {

  public static void main(String[] args) {
    System.out.println(A$B.class.getName());
  }

}
mac-grek:javajunk grek$ javac A$B.java Main.java
mac-grek:javajunk grek$ 

So Java allows me to define a class containing dollar sign in it's name. How can I compile my original example?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have a name conflict because you defined a top-level class A$B having the same name as the generated name for a static inner class B of class A. Since you have both, the compiler can't resolve the conflict.

The JLS says:

The $ character should be used only in mechanically generated source code or, rarely, to access pre-existing names on legacy systems.

Since you decided not to respect that rule, you got bitten by javac. I would just rename A$B to something else.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...