Name和CanonicalName之间的区别是什么?

时间:2013-04-09 13:46:22

标签: java class names canonical-name

Java的Class.getName()Class.getCanonicalName()之间有什么区别?

1 个答案:

答案 0 :(得分:17)

考虑以下计划:

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

输出:

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()返回null的原因。