关于java:Name和CanonicalName有什么区别?

What's the difference between Name and CanonicalName?

本问题已经有最佳答案,请猛点这里访问。

Java的EDOCX1 0和EDCOX1 1的区别是什么?


考虑以下程序:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package org.test.stackoverflow;

public class CanonicalName {

  public static void main(String[] args) {
    CanonicalName cn = new CanonicalName();
    cn.printClassNames();
  }

  private Anonymous anony;
  private MyAnony myAnony;

  public CanonicalName() {
    anony = new Anonymous() {
      public void printInterface() {
        System.out.println("Anony Name:" + getClass().getName());
        System.out.println("Anony CanonicalName:" + getClass().getCanonicalName());
      }
    };
    myAnony = new MyAnony();
  }

  public void printClassNames() {
    System.out.println("CanonicalName, Name:" + getClass().getName());
    System.out.println("CanonicalName, CanonicalName:" + getClass().getCanonicalName());
    anony.printInterface();
    myAnony.printInterface();
  }

  private static interface Anonymous {
    public void printInterface();
  }

  private static class MyAnony implements Anonymous {
    public void printInterface() {
      System.out.println("MyAnony Name:" + getClass().getName());
      System.out.println("MyAnony CanonicalName:" + getClass().getCanonicalName());
    }
  }
}

输出:

1
2
3
4
5
6
CanonicalName, Name: org.test.stackoverflow.CanonicalName
CanonicalName, CanonicalName: org.test.stackoverflow.CanonicalName
Anony Name: org.test.stackoverflow.CanonicalName$1
Anony CanonicalName: null
MyAnony Name: org.test.stackoverflow.CanonicalName$MyAnony
MyAnony CanonicalName: org.test.stackoverflow.CanonicalName.MyAnony

因此,对于基类,它们返回相同的东西。对于内部类,getName()使用$命名约定(即用于.class文件的内容),getCanonicalName()返回在试图实例化类时将使用的内容。你不能用(一个小的)匿名类来实现这一点,所以getCanonicalName()返回空值。