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

后端 未结 8 1219
感动是毒
感动是毒 2020-11-27 08:58

In Java, what is the difference between these:

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


        
8条回答
  •  感动是毒
    2020-11-27 09:19

    this is best document I found describing getName(), getSimpleName(), getCanonicalName()

    https://javahowtodoit.wordpress.com/2014/09/09/java-lang-class-what-is-the-difference-between-class-getname-class-getcanonicalname-and-class-getsimplename/

    // Primitive type
    int.class.getName();          // -> int
    int.class.getCanonicalName(); // -> int
    int.class.getSimpleName();    // -> int
    
    // Standard class
    Integer.class.getName();          // -> java.lang.Integer
    Integer.class.getCanonicalName(); // -> java.lang.Integer
    Integer.class.getSimpleName();    // -> Integer
    
    // Inner class
    Map.Entry.class.getName();          // -> java.util.Map$Entry
    Map.Entry.class.getCanonicalName(); // -> java.util.Map.Entry
    Map.Entry.class.getSimpleName();    // -> Entry     
    
    // Anonymous inner class
    Class anonymousInnerClass = new Cloneable() {}.getClass();
    anonymousInnerClass.getName();          // -> somepackage.SomeClass$1
    anonymousInnerClass.getCanonicalName(); // -> null
    anonymousInnerClass.getSimpleName();    // -> // An empty string
    
    // Array of primitives
    Class primitiveArrayClass = new int[0].getClass();
    primitiveArrayClass.getName();          // -> [I
    primitiveArrayClass.getCanonicalName(); // -> int[]
    primitiveArrayClass.getSimpleName();    // -> int[]
    
    // Array of objects
    Class objectArrayClass = new Integer[0].getClass();
    objectArrayClass.getName();          // -> [Ljava.lang.Integer;
    objectArrayClass.getCanonicalName(); // -> java.lang.Integer[]
    objectArrayClass.getSimpleName();    // -> Integer[]
    

提交回复
热议问题