Methods to get the class name
There are three main ways to get class names in Java.
Returned is the class name representation of the classes inside the virtual machine.
Returns the class name representation that is easier to understand.
The return is the short name of the class.
What's the difference?
Look at their main differences through an example.
public class TestClass {public static void main (string[] args) {//External common Class System.out.println ("method name Class name "); System.out.println ("GetName" + TestClass.class.getName ()); System.out.println ("Getcanonicalname" + TestClass.class.getCanonicalName ()); System.out.println ("Getsimplename" + TestClass.class.getSimpleName ()); System.out.println (); Internal class System.out.println ("GetName" + TestInnerClass.class.getName ()); System.out.println ("Getcanonicalname" + TestInnerClass.class.getCanonicalName ()); System.out.println ("Getsimplename" + TestInnerClass.class.getSimpleName ()); System.out.println (); Array class testinnerclass[] testinnerclasses = new testinnerclass[]{new Testinnerclass (), New Testinnerclass (), New Testinnerclass ()}; System.out.println ("GetName" + testinnerclasses.getclass (). GetnAme ()); System.out.println ("Getcanonicalname" + testinnerclasses.getclass (). Getcanonicalname ()); System.out.println ("Getsimplename" + testinnerclasses.getclass (). Getsimplename ()); System.out.println (); } static class Testinnerclass {}}
The program outputs the following results.
方法名 类名getName com.test.TestClassgetCanonicalName com.test.TestClassgetSimpleName TestClassgetName com.test.TestClass$TestInnerClassgetCanonicalName com.test.TestClass.TestInnerClassgetSimpleName TestInnerClassgetName [Lcom.test.TestClass$TestInnerClass;getCanonicalName com.test.TestClass.TestInnerClass[]getSimpleName TestInnerClass[]
[Lcom.test.TestClass$TestInnerClass;
Worth explaining.
This is an encoding of the function return values and parameters, called the Jni field descriptor (javanative Interface fielddescriptors).
[
Represents an array, one that represents a one-dimensional array, such as a [[
two-dimensional array. L
the class descriptor is then represented, and finally the ;
class name ends.
Conclusion
1, from the above results can be seen GetName () and Getcanonicalname () in obtaining the ordinary class name when there is no difference between the acquisition of the inner class and array classes.
2. Getsimplename () has no difference when getting the ordinary class and the inner class name, and there is a difference when getting the array class.
Recommended: Spring Boot & Cloud's Strongest technology tutorials
Scan attention to our public number, dry foods updated daily.
3 Ways to get the class name in Java!