[英]Java get declaring class for an abstract class?
Does anyone know how to get the declaring / enclosing class of an abstract class in Java? 有谁知道如何在Java中获取抽象类的声明/封闭类? In this case, I would like to get the anotherClass class from within someClass. 在这种情况下,我想从someClass中获取anotherClass类。
Example: 例:
public class anotherClass extends someClass{
...
}
public abstract class someClass{
...
this.getClass().getEnclosingClass();
}
没有反射就无法做到这一点
If you call this.getClass()
in an abstract class it will still return the class of the actual implementation. 如果您在抽象类中调用this.getClass()
,它将仍然返回实际实现的类。 In your case calling this.getClass()
will return anotherClass
, which is what you want if I am not wrong. 在您的情况下,调用this.getClass()
将返回anotherClass
,如果我没有记错的话,这就是您想要的。
If you want to avoid the reflection solution, you can force people to pass you themselves with some curiously recurring generics, like the following: 如果要避免使用反射解决方案,则可以强制人们使用一些奇怪的重复出现的泛型来使自己过关,例如:
class AnotherClass extends SomeClass<AnotherClass> {
public AnotherClass() {
super(AnotherClass.class);
}
}
abstract class SomeClass<T extends SomeClass<T>> {
final Class<T> enclosing;
public SomeClass(Class<T> c) {
enclosing = c;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.