Java 为抽象类声明类吗?
有谁知道如何在Java中获取抽象类的声明/封闭类?在这种情况下,我想从 someClass 中获取 anotherClass 类。
例子:
public class anotherClass extends someClass{
...
}
public abstract class someClass{
...
this.getClass().getEnclosingClass();
}
Does anyone know how to get the declaring / enclosing class of an abstract class in Java? In this case, I would like to get the anotherClass class from within someClass.
Example:
public class anotherClass extends someClass{
...
}
public abstract class someClass{
...
this.getClass().getEnclosingClass();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果不使用
There is no way to do this without using reflection
如果您在抽象类中调用 this.getClass() ,它仍然会返回实际实现的类。在您的情况下,调用
this.getClass()
将返回anotherClass
,如果我没有错的话,这就是您想要的。If you call
this.getClass()
in an abstract class it will still return the class of the actual implementation. In your case callingthis.getClass()
will returnanotherClass
, which is what you want if I am not wrong.如果您想避免反射解决方案,您可以强迫人们使用一些奇怪的重复泛型自行传递给您,如下所示:
If you want to avoid the reflection solution, you can force people to pass you themselves with some curiously recurring generics, like the following: