Class.getName()
Javaとはどう違いClass.getCanonicalName()
ますか?
9420 次
1 に答える
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 が返されます。
于 2013-04-09T13:46:21.603 に答える