是否可以将泛型添加到枚举值?包含示例伪代码

发布于 2024-12-11 03:41:05 字数 390 浏览 2 评论 0原文

是否可以将泛型添加到枚举值?

与此伪代码类似的东西:

    public enum MyEnum<T> {

            VALUE1<String>,
            VALUE2<Boolean>;

            public T get() {
                    return (T) AnotherSystem.get(this); // Where AnotherSystem.get returns an Object
            }

    }

我刚刚写错了,还是这根本不可能?

我还需要哪些其他选项才能使 get() 返回特定的泛型类型 (T)

Is it possible to add generics to enum values?

Something similar to this pseudo code:

    public enum MyEnum<T> {

            VALUE1<String>,
            VALUE2<Boolean>;

            public T get() {
                    return (T) AnotherSystem.get(this); // Where AnotherSystem.get returns an Object
            }

    }

Have I just written this incorrectly, or is this not possible at all?

What other options do I have to make get() return a specific generic type (T)

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

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

发布评论

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

评论(2

陌上芳菲 2024-12-18 03:41:05

如果您需要

        public <T> T get() {
                return (T) AnotherSystem.get(this); 
        }

将类型与枚举关联起来,它可以是属性

public enum MyEnum {

    VALUE1(String.class),
    VALUE2(Boolean.class);

    public final Class<?> type;
    MyEnum(Class<?> type){ this.type = type; }

    public <T> T get() {
        return (T) AnotherSystem.get(this, this.type);
    }

}

class AnotherSystem
{
    static<T> T get(MyEnum e, Class<T> type){ return null; }
}

You can do

        public <T> T get() {
                return (T) AnotherSystem.get(this); 
        }

If you need to associate a type with an enum, it can be a property

public enum MyEnum {

    VALUE1(String.class),
    VALUE2(Boolean.class);

    public final Class<?> type;
    MyEnum(Class<?> type){ this.type = type; }

    public <T> T get() {
        return (T) AnotherSystem.get(this, this.type);
    }

}

class AnotherSystem
{
    static<T> T get(MyEnum e, Class<T> type){ return null; }
}
提笔落墨 2024-12-18 03:41:05

不,我不相信这样的事情是可能的。如果您查看JLS 的第 8.9 节 ,在指定枚举声明的地方,那里没有任何关于泛型的内容:

将其与 第 8.1 节,其中规范的一部分是类型涉及的参数。

No, I don't believe anything like this is possible. If you look at section 8.9 of the JLS, where enum declarations are specified, there's nothing about generics there:

Compare it with the "normal" class declaration in section 8.1, where part of the spec is the type parameters involved.

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