[英]Java, Get Class object for containing class, Not Runtime Class
Consider this Java code 考虑这个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)
inside f()
i can't use getClass()
because that will give me the runtype, which is B
. 在f()
里面我不能使用getClass()
因为这会给我一个runtype,即B
I'm looking for a way to get the Class
object of the class
f()
is inside (Without mentioning A
explicitly, obviously) 我正在寻找一种方法来获取class
f()
的Class
对象在里面(显然没有明确提到A
)
new Object() {}.getClass().getEnclosingClass()
. new Object() {}.getClass().getEnclosingClass()
。 But please don't! 但请不要!
You can use exception stack trace facility to do something like this: 您可以使用异常堆栈跟踪工具来执行以下操作:
public String f() {
Exception E = new Exception();
E.fillInStackTrace();
return E.getStackTrace()[0].getClassName(); // load it if you need to return class
}
I would have to say it would be much simpler and more clear to simply return A.class as @mmyers suggested. 我不得不说,简单地返回A.class就像@mmyers建议的那样简单明了。 There is not much point in trying to derive it at runtime if you don't actually want the runtime value. 如果您实际上不想要运行时值,那么在运行时尝试派生它没有多大意义。 The only issue that comes up is if you refactor the name of the class and another with the same name happens to exist, in the same package. 出现的唯一问题是,如果您重构类的名称,并且在同一个包中存在同名的另一个。
I would take that chance for the sake of clarity in the code now. 为了清楚起见,我现在就抓住这个机会了。
您可以使用
class.getMethod("f",parameterTypes).getDeclaringClass()
I know you said you didn't want to mention A.class explicitly 我知道你说你不想明确提到A.class
class A {
public Class<?> f() {
return A.class;
}
}
but I'm struggling to find a use case where the above code isn't satisfactory. 但我很难找到一个上述代码不满意的用例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.