<分区>
Java 的 Class.getName()
和 Class.getCanonicalName()
有什么区别?
<分区>
Java 的 Class.getName()
和 Class.getCanonicalName()
有什么区别?
最佳答案
考虑以下程序:
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 的原因。
关于java - 名称和规范名称有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15903672/