使用另一个类的字段类型实例化参数化类

发布于 2024-12-15 05:21:12 字数 583 浏览 2 评论 0原文

我想使用从类字段(使用反射)获取的类型来实例化带有泛型的类。
注意:为了便于阅读,我省略了例外情况。

public class AClass   {
    class BClass<T>   {
        T aMemba;
    }

    public void AMethod()   {
        Class c = Class.forName("com.bla.flipper");
        Field f = c.getField("flipIt");

        // Here is my difficulty, I want to instantiate BClass with the type of
        // field 'f' but the compiler won't let me.
        Class typeClass = f.getType();
        BClass<typeClass> = new BClass<typeClass>();
    }
}

我想要达到的目标合理吗?关于如何解决这个问题有什么想法吗?

谢谢!

I would like to use a type which I get from a class' field (using reflection) to instantiate a class with generics.
Note: I omitted the exceptions hoping for easy reading.

public class AClass   {
    class BClass<T>   {
        T aMemba;
    }

    public void AMethod()   {
        Class c = Class.forName("com.bla.flipper");
        Field f = c.getField("flipIt");

        // Here is my difficulty, I want to instantiate BClass with the type of
        // field 'f' but the compiler won't let me.
        Class typeClass = f.getType();
        BClass<typeClass> = new BClass<typeClass>();
    }
}

Is what I want to achieve reasonable? Any thought on how I can solve this problem?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

脱离于你 2024-12-22 05:21:12

无论您尝试做什么都是不合理的,因为如果您查看以下行:

BClass<typeClass> = new BClass<typeClass>();

typeClass 是编译器应该注意的事情。但在你的情况下,它只能在运行时通过反射知道。

编译器需要删除 BClass 中的 T 并将其替换为具体类型,在您的情况下,该类型在编译时未知,因此逻辑上它是无效的。

Whatever you are trying to do is not reasonable because if you look at the following line:

BClass<typeClass> = new BClass<typeClass>();

typeClass is something that compiler should be aware of. But in your case it's only known in the runtime through reflection.

Compiler needs to erase T in BClass<T> and replace it with a concrete type which in your case is unknown at compile time so logically it's invalid.

不如归去 2024-12-22 05:21:12

您可以捕获 typeClass 类型的类型参数:

Field f = ...;
Class<?> typeClass = f.getType();
withClassCapture(typeClass);

private <T> void withClassCapture(Class<T> klazz) {
    BClass<T> instance = new BClass<T>();
    // ... do your thing
}

You can capture the type argument of the type of typeClass:

Field f = ...;
Class<?> typeClass = f.getType();
withClassCapture(typeClass);

private <T> void withClassCapture(Class<T> klazz) {
    BClass<T> instance = new BClass<T>();
    // ... do your thing
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文