简体   繁体   中英

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

Why is this possible in Java:

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

Why is there this infinite recursion?

Just curious.

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() .

A Class object 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>>>

Eventually you'll run out of stack memory, time, or disk space for such a huge program, or reach a Java internal limit.

Every class extends the Object class. Class being a class itself it inheritates the getClass() method. Allowing you to call Class#getClass().getClass() and so on.

That's not recursion.

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

For example:

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

What you have done is call a method to get this object's class and then getting the class of the class ( java.lang.Class ) and repeating it for as long as you care to type.

public final Class<? extends Object> getClass()

getClass() returns a Class object. Since Class is a derivative of Object, it too has a getClass method. You should print a few iterations. You should notice a repeating pattern after the first call...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM