Java基础-class.getXXName的区别

原创
2020/03/23 18:04
阅读数 49

以下会输出什么?是否所有的类输出的结果都是一样的?

Object o1 = ....
o1.getClass().getSimpleName();
o1.getClass().getName();
o1.getClass().getCanonicalName();

我们来实验下

class ClassNameTest {
    public static void main(final String... arguments) {
        printNamesForClass(
            int.class,
            "int.class (primitive)");
        printNamesForClass(
            String.class,
            "String.class (ordinary class)");
        printNamesForClass(
            java.util.HashMap.SimpleEntry.class,
            "java.util.HashMap.SimpleEntry.class (nested class)");
        printNamesForClass(
            new java.io.Serializable(){}.getClass(),
            "new java.io.Serializable(){}.getClass() (anonymous inner class)");
    }

    private static void printNamesForClass(final Class<?> clazz, final String label) {
        System.out.println(label + ":");
        System.out.println("    getName():          " + clazz.getName());
        System.out.println("    getCanonicalName(): " + clazz.getCanonicalName());
        System.out.println("    getSimpleName():    " + clazz.getSimpleName());
        System.out.println("    getTypeName():      " + clazz.getTypeName()); // added in Java 8
        System.out.println();
    }
}

输出结果:

int.class (primitive):
    getName():          int
    getCanonicalName(): int
    getSimpleName():    int
    getTypeName():      int

String.class (ordinary class):
    getName():          java.lang.String
    getCanonicalName(): java.lang.String
    getSimpleName():    String
    getTypeName():      java.lang.String

java.util.HashMap.SimpleEntry.class (nested class):
    getName():          java.util.AbstractMap$SimpleEntry
    getCanonicalName(): java.util.AbstractMap.SimpleEntry
    getSimpleName():    SimpleEntry
    getTypeName():      java.util.AbstractMap$SimpleEntry

new java.io.Serializable(){}.getClass() (anonymous inner class):
    getName():          ClassNameTest$1
    getCanonicalName(): null
    getSimpleName():    
    getTypeName():      ClassNameTest$1

There's an empty entry in the last block where getSimpleName returns an empty string.

The upshot looking at this is:

  • the name is the name that you'd use to dynamically load the class with, for example, a call to Class.forName with the default ClassLoader. Within the scope of a certain ClassLoader, all classes have unique names.
  • the canonical name is the name that would be used in an import statement. It might be useful during toString or logging operations. When the javac compiler has complete view of a classpath, it enforces uniqueness of canonical names within it by clashing fully qualified class and package names at compile time. However JVMs must accept such name clashes, and thus canonical names do not uniquely identifies classes within a ClassLoader. (In hindsight, a better name for this getter would have been getJavaName; but this method dates from a time when the JVM was used solely to run Java programs.)
  • the simple name loosely identifies the class, again might be useful during toString or logging operations but is not guaranteed to be unique.
  • the type name returns "an informative string for the name of this type", "It's like toString(): it's purely informative and has no contract value" (as written by sir4ur0n)

Fully Qualified Names and Canonical Names

Every primitive type, named package, top level class, and top level interface has a fully qualified name:

  • The fully qualified name of a primitive type is the keyword for that primitive type, namely byte, short, char, int, long, float, double, or boolean.

  • The fully qualified name of a named package that is not a subpackage of a named package is its simple name.

  • The fully qualified name of a named package that is a subpackage of another named package consists of the fully qualified name of the containing package, followed by ".", followed by the simple (member) name of the subpackage.

  • The fully qualified name of a top level class or top level interface that is declared in an unnamed package is the simple name of the class or interface.

  • The fully qualified name of a top level class or top level interface that is declared in a named package consists of the fully qualified name of the package, followed by ".", followed by the simple name of the class or interface.

Each member class, member interface, and array type may have a fully qualified name:

  • A member class or member interface M of another class or interface C has a fully qualified name if and only if C has a fully qualified name.

  • In that case, the fully qualified name of M consists of the fully qualified name of C, followed by ".", followed by the simple name of M.

  • An array type has a fully qualified name if and only if its element type has a fully qualified name.

  • In that case, the fully qualified name of an array type consists of the fully qualified name of the component type of the array type followed by "[]".

A local class does not have a fully qualified name.

Example 6.7-1. Fully Qualified Names

The fully qualified name of the type long is "long".

The fully qualified name of the package java.lang is "java.lang" because it is subpackage lang of package java.

The fully qualified name of the class Object, which is defined in the package java.lang, is "java.lang.Object".

The fully qualified name of the interface Enumeration, which is defined in the package java.util, is "java.util.Enumeration".

The fully qualified name of the type "array of double" is "double[]".

The fully qualified name of the type "array of array of array of array of String" is "java.lang.String[][][][]".

In the code:

package points;
class Point    { int x, y; }
class PointVec { Point[] vec; }
the fully qualified name of the type Point is "points.Point"; the fully qualified name of the type PointVec is "points.PointVec"; and the fully qualified name of the type of the field vec of class PointVec is "points.Point[]".

Every primitive type, named package, top level class, and top level interface has a canonical name:

  • For every primitive type, named package, top level class, and top level interface, the canonical name is the same as the fully qualified name.

Each member class, member interface, and array type may have a canonical name:

  • A member class or member interface M declared in another class C has a canonical name if and only if C has a canonical name.

In that case, the canonical name of M consists of the canonical name of C, followed by ".", followed by the simple name of M.

  • An array type has a canonical name if and only if its component type has a canonical name.

In that case, the canonical name of the array type consists of the canonical name of the component type of the array type followed by "[]".

A local class does not have a canonical name.

Example 6.7-2. Fully Qualified Names v. Canonical Name

The difference between a fully qualified name and a canonical name can be seen in code such as:

package p;
class O1 { class I {} }
class O2 extends O1 {}
Both p.O1.I and p.O2.I are fully qualified names that denote the member class I, but only p.O1.I is its canonical name.

参考资料

What is the difference between canonical name, simple name and class name in Java Class?

Fully Qualified Names and Canonical Names

展开阅读全文
打赏
0
0 收藏
分享
加载中
你好,看了你的文章,觉得你是一名对技术很有追求的同学
请问有兴趣加入菜鸟国际物流技术部吗,今年会主攻俄罗斯那边的项目,有机会去实地看看的,感兴趣吗
2020/03/23 19:26
回复
举报
更多评论
打赏
1 评论
0 收藏
0
分享
返回顶部
顶部