Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this possible in Java: this.getClass().getClass().getClass()....etc

Tags:

java

class

Why is this possible in Java:

this.getClass().getClass().getClass().getClass()...

Why is there this infinite recursion?

Just curious.

like image 270
Alexander Mills Avatar asked Oct 14 '13 15:10

Alexander Mills


People also ask

Why do we use getClass in Java?

The getClass() method of Writer Class in Java is used to get the parent Class of this Writer instance. This method does not accepts any parameter and returns the required Class details.

What does getClass () getName () Do Java?

Java Class getName() Method The getName() method of java Class class is used to get the name of the entity, and that entity can be class, interface, array, enum, method, etc. of the class object.

How does the getClass method work?

getClass() is the method of Object class. This method returns the runtime class of this object. The class object which is returned is the object that is locked by static synchronized method of the represented class.

What is the difference between getClass and .Class in Java?

getClass() method can give us the Class object of its runtime type. As the test above shows, the . class syntax can obtain the Class objects for those types. Therefore, when we want to have the Class object, but we cannot get an instance of the type, the .


1 Answers

There's no infinite recursion here: getClass() returns a java.lang.Class object, which is itself a java.lang.Object object, hence it supports getClass() method. After the second call to getClass() you are going to get the same result, no matter how many times you call getClass().

like image 78
Sergey Kalinichenko Avatar answered Nov 04 '22 13:11

Sergey Kalinichenko