The difference between .getClass and .class, usage

.getclass() is under the Java.long.Object class;

Returns the class object of this object at runtime

1, get the type class

We know that everything in Java is an object, and the objects we generally use inherit directly or indirectly from the Object class. The Object class contains a method named getClass, which can be used to obtain the type class of an instance . A type class refers to a class that represents a type, because everything is an object, and types are no exception. In Java, a type class is used to represent a type. All type classes are instances of the Class class. For example, there is the following piece of code:

  1. A a = new A();  
  2.   
  3. if(a.getClass()==A.class) {  
  4.   
  5.       System.out.println("equal");  
  6.   
  7. else {  
  8.   
  9.       System.out.println("unequal");  
  10.   
  11. }  
  12. output equal;  

a is an instantiated object of class A that is returned in the if statement is the class of type A.
A specific type class in Java can be obtained as "type.class". Because a.getclass() gets exactly the type A class, which is A.class

So the result is equals. It is important to note that the type classes are in a one-to-one correspondence, and the type class of the parent class and the type class of the child class are different , so, assuming that A is a child class of B, the following code will get " unequal" output:
[java]  view plain copy  
 
  1. A a = new A();  
  2.   
  3. if(a.getClass()==B.class) {  
  4.   
  5.         System.out.println("equal");  
  6.   
  7. }  else {  
  8.           
  9.           System.out.println("unequal");  
  10. }  
  11. output unequal;  

So, if you know an instance, then you can get the object's type class through the instance's "getClass()" method, and if you know a type, then you can use the ".class" method to get the type class of that type.

getName():String: Get the full name of the type.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325213714&siteId=291194637