gpt4 book ai didi

Java - this.getClass() 在参数化类方法中返回什么编译时类?

转载 作者:行者123 更新时间:2023-11-30 08:36:13 25 4
gpt4 key购买 nike

我见过类似的问题并且有一个可行的解决方案,但我没有深入理解为什么我的示例中的前四次尝试(c1、c2、c3 和 c4)无法编译。归结为我不理解 this.getClass() 返回的编译时类是什么。

import java.lang.reflect.*;

public class MyClass<T extends MyClass<?>> {

public Constructor<T> findConstructor()
throws NoSuchMethodException {

Class<? extends MyClass<T>> c1 = this.getClass(); // what I expect from getClass() documentation
Class<? extends T> c2 = this.getClass(); // what I'd like even better
Class<T> c3 = this.getClass(); // this would be fine too
Class<MyClass> c4 = this.getClass(); // I'd even accept this, losing the T parameter
@SuppressWarnings("unchecked")
Class<T> c5 = (Class<T>) this.getClass(); // works, but eww

Constructor<T> constructor = c5.getConstructor(); // my goal

return constructor;
} // findConstructor()

} // MyClass<T>

有人吗?谢谢。

最佳答案

getClass() 的 Javadoc (强调来自 javadoc):

Returns the runtime class of this Object. The returned Class object is the object that is locked by static synchronized methods of the represented class.

The actual result type is Class<? extends |X|> where |X| is the erasure of the static type of the expression on which getClass is called. For example, no cast is required in this code fragment:

Number n = 0;
Class<? extends Number> c = n.getClass();

所以,因为你的类(class)是 MyClass<T extends MyClass<?>> , 删除是 MyClass ,这意味着 |X|MyClass ,因此实际结果类型是:

Class<? extends MyClass>

前 4 个语句与该类型的赋值不兼容,第 5 个语句将通过类转换编译。


因为删除意味着你不知道是什么T在运行时,无法返回构造函数以键入 T .

记住,T不必是 MyClass 的同一个子类用于调用findConstructor() .示例:

public class Foo extends MyClass<Foo> {
}
public class Bar extends MyClass<Foo> {
}

如果您调用了 bar.findConstructor() ,它根本无法将构造函数返回给 Foo ,因为它不知道 TFoo在运行时(由于类型删除)。

关于Java - this.getClass() 在参数化类方法中返回什么编译时类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37872051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com