名称和规范名称有什么区别?

2022-09-04 02:40:22

Java 和 ?Class.getName()Class.getCanonicalName()


答案 1

请考虑以下程序:

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

因此,对于基类,它们似乎返回相同的内容。对于内部类,使用命名约定(即用于.class文件的内容),并返回在尝试实例化类时将使用的内容。你不能用(little-a)匿名类做到这一点,所以这就是返回null的原因。getName()$getCanonicalName()getCanonicalName()


答案 2