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

后端 未结 8 1189
感动是毒
感动是毒 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:12

    getName() – returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String.

    getCanonicalName() – returns the canonical name of the underlying class as defined by the Java Language Specification.

    getSimpleName() – returns the simple name of the underlying class, that is the name it has been given in the source code.

    package com.practice;
    
    public class ClassName {
    public static void main(String[] args) {
    
      ClassName c = new ClassName();
      Class cls = c.getClass();
    
      // returns the canonical name of the underlying class if it exists
      System.out.println("Class = " + cls.getCanonicalName());    //Class = com.practice.ClassName
      System.out.println("Class = " + cls.getName());             //Class = com.practice.ClassName
      System.out.println("Class = " + cls.getSimpleName());       //Class = ClassName
      System.out.println("Class = " + Map.Entry.class.getName());             // -> Class = java.util.Map$Entry
      System.out.println("Class = " + Map.Entry.class.getCanonicalName());    // -> Class = java.util.Map.Entry
      System.out.println("Class = " + Map.Entry.class.getSimpleName());       // -> Class = Entry 
      }
    }
    

    One difference is that if you use an anonymous class you can get a null value when trying to get the name of the class using the getCanonicalName()

    Another fact is that getName() method behaves differently than the getCanonicalName() method for inner classes. getName() uses a dollar as the separator between the enclosing class canonical name and the inner class simple name.

    To know more about retrieving a class name in Java.

提交回复
热议问题