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

Why is this possible in Java:

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

Why does this infinite recursion exist?

Just curious.

+6
source share
5 answers
An object

A Class is still an object, and you can call getClass on any object, thanks to the existence of Object#getClass . So you get:

 this.getClass(); // Class<YourClass> this.getClass().getClass(); // Class<Class<YourClass>> this.getClass().getClass().getClass(); //Class<Class<Class<YourClass>>> 

In the end, you will run out of memory, time or disk space for such a huge program, or have reached the internal Java limit.

+3
source

There is no endless recursion: getClass() returns a java.lang.Class object, which itself is a java.lang.Object object, therefore it supports the getClass() method. After the second call to getClass() you will get the same result, no matter how many times you call getClass() .

+10
source

Each class extends the Object class. Class is the class itself, which inherits the getClass() method. Lets you call Class#getClass().getClass() , etc.

+2
source

This is not recursion.

Recursion is where the method calls itself (defining freely) for a finite number of times before it finally returns.

For instance:

 public int sumUpTo(int i) { if (i == 1) { return 1; } else { return i + sumUpTo(i-1); } } 

What you did is call the method to get this class of the object, and then get the class of the class ( java.lang.Class ) and repeat it until you want to enter.

+1
source
 public final Class<? extends Object> getClass() 

getClass () returns a Class object. Since the class is derived from Object, it also has a getClass method. You should print some iterations. You should notice a repeating pattern after the first call ...

+1
source

Source: https://habr.com/ru/post/955919/


All Articles