简体   繁体   English

为什么在Java中这是可能的:this.getClass()。getClass()。getClass()...等

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

Why is this possible in Java: 为什么这在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. 这里没有无限递归: getClass()返回一个java.lang.Class对象,它本身就是一个java.lang.Object对象,因此它支持getClass()方法。 After the second call to getClass() you are going to get the same result, no matter how many times you call getClass() . 在第二次调用getClass()之后,无论调用getClass()多少次,都会得到相同的结果。

A Class object is still an object, and you can call getClass on any object, thanks to the existence of Object#getClass . Class对象仍然是一个对象,你可以在任何对象上调用getClass ,这要归功于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. 最终,对于如此庞大的程序,您将耗尽堆栈内存,时间或磁盘空间,或达到Java内部限制。

Every class extends the Object class. 每个类都扩展了Object类。 Class being a class itself it inheritates the getClass() method. Class是一个类本身,它继承了getClass()方法。 Allowing you to call Class#getClass().getClass() and so on. 允许您调用Class#getClass().getClass()等。

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. 你所做的是调用一个方法来获取这个对象的类,然后获取类的类( java.lang.Class )并重复它,只要你愿意输入。

public final Class<? extends Object> getClass()

getClass() returns a Class object. getClass()返回一个Class对象。 Since Class is a derivative of Object, it too has a getClass method. 由于Class是Object的衍生物,因此它也有一个getClass方法。 You should print a few iterations. 你应该打印几次迭代。 You should notice a repeating pattern after the first call... 在第一次通话后你应该注意到一个重复的模式......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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