Java 为抽象类声明类吗?

发布于 2025-01-07 08:45:36 字数 241 浏览 1 评论 0原文

有谁知道如何在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

小伙你站住 2025-01-14 08:45:36

如果不使用

There is no way to do this without using reflection

风追烟花雨 2025-01-14 08:45:36

如果您在抽象类中调用 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 calling this.getClass() will return anotherClass, which is what you want if I am not wrong.

牵强ㄟ 2025-01-14 08:45:36

如果您想避免反射解决方案,您可以强迫人们使用一些奇怪的重复泛型自行传递给您,如下所示:

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;
    }
}

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;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文