gpt4 book ai didi

Java,获取包含类的类对象,而不是运行时类

转载 作者:行者123 更新时间:2023-12-03 23:08:23 24 4
gpt4 key购买 nike

考虑这段 Java 代码

class A{
//@returns Class object this method is contained in
// should be A in this case
public Class<?> f() {
return getClass();
}
}

class B extends A {}

B b = new B();

System.out.println(b.f());
//output -- B.class (Wrong, should be A.class)

f() 中,我不能使用 getClass(),因为它会给我运行类型,即 B。我正在寻找一种方法来获取 class f()Class 对象在里面(没有提到 A明确地,显然地)

最佳答案

new Object() {}.getClass().getEnclosingClass()。但请不要!

关于Java,获取包含类的类对象,而不是运行时类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1507257/

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