枚举和通用常量具体方法

发布于 2024-09-28 20:32:56 字数 413 浏览 2 评论 0原文

我有一个枚举,例如:

    enum TEST {
        TEST1, TEST 2;

        public abstract <T> String stringify (T input);
    }

我需要添加一个常量特定方法,例如 stringify。

此方法将采用不同类型的输入(对于每个枚举)。我可以这样做吗? Eclipse 不让我这样做..比如:

enum TEST {
    TEST1(
       public <Float> String stringify (Float input){
          return String.valueOf(input);
        }
    )
}

I have an enum like:

    enum TEST {
        TEST1, TEST 2;

        public abstract <T> String stringify (T input);
    }

I need to add a constant specific method , something like stringify.

This method will take different types of inputs (for each enum). Can I do that? Eclipse is not letting me do it ..something like:

enum TEST {
    TEST1(
       public <Float> String stringify (Float input){
          return String.valueOf(input);
        }
    )
}

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

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

发布评论

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

评论(5

橪书 2024-10-05 20:32:57

不,您不能使每个枚举常量实现抽象方法,但需要与其他枚举常量不同类型的输入。如果可以的话,如果给您一个 TEST 枚举实例(您不知道它是什么常量)并尝试对其调用 stringify ,会发生什么?你会通过什么类型的?

编辑:鉴于您所说的这些枚举用于将字符串解码为对象,在我看来,您有多种选择:

  • 您可以获得每个枚举的 String 表示形式只需调用 toString() 即可解码对象。
  • 您可以在枚举类本身上添加一组重载静态方法,称为 stringify(Float)stringify(Double) 等。然后您只需调用 TEST.stringify(value) 并且如果值的类型有一个 stringify 方法,那么它就可以正常工作。

我想还有其他选择。

No, you can't make each enum constant implement an abstract method but require a different type of input than the other enum constants. If you could, what would happen if you were given an instance of your TEST enum (you don't know what constant it is) and tried to call stringify on it? What type would you pass it?

Edit: Given what you've said about these enums being used to decode strings into objects, it seems to me you have several options:

  • You could get a String representation of each decoded object by just calling toString() on it.
  • You could add a set of overloaded static method on the enum class itself, called stringify(Float) and stringify(Double), etc. Then you could just call TEST.stringify(value) and if there were a stringify method for the value's type, it'd work fine.

I imagine there are other options as well.

感情旳空白 2024-10-05 20:32:57

您不能将泛型与枚举一起使用,因为枚举常量本身已经是具体(单例)实例。在实例级别,泛型必须已经是具体的。
因此,我强烈建议采用其他答案中给出的替代方案之一。

如果必须在枚举中执行此操作,则可以考虑以下方法,它至少为您提供了类型检查的运行时方法,包括 ClassCastExceptions。不过,您不会获得编译器的任何支持。

public enum TestEnum {
    Test1(Float.class),
    Test2(Integer.class),
    Test3(String.class);

    private final Class<?> iInputType;

    private TestEnum(final Class<?> pInputType) {
        iInputType = pInputType;
    }

    public Class<?> getInputType() {
        return iInputType;
    }

    public String stringify(final Object pInput) {
        return String.valueOf(iInputType.cast(pInput));
    }
}

测试代码:

System.out.println(TestEnum.Test1.stringify(1.23f));
System.out.println(TestEnum.Test2.stringify(42));
System.out.println(TestEnum.Test3.stringify("foo"));
// but:
// System.out.println(TestEnum.Test1.stringify("foo")); // -> ClassCastException!

for (TestEnum test : TestEnum.values()) {
    for (Object input : new Object[]{1.23f, 42, "foo"}) {
        if (test.getInputType().isAssignableFrom(input.getClass())) {
            System.out.println(test.stringify(input));
        }
    }
}

You can't use generics with enums, because the enum constants themselves are already the concrete (singleton) instances. At instance level, the generics must already be concrete.
So, I would stringly recommend going with one of the alternatives given in the other answers.

If you must do it in an enum, you could consider the following, which at least gives you a runtime means of type checking, including ClassCastExceptions. You won't have any support from the compiler though.

public enum TestEnum {
    Test1(Float.class),
    Test2(Integer.class),
    Test3(String.class);

    private final Class<?> iInputType;

    private TestEnum(final Class<?> pInputType) {
        iInputType = pInputType;
    }

    public Class<?> getInputType() {
        return iInputType;
    }

    public String stringify(final Object pInput) {
        return String.valueOf(iInputType.cast(pInput));
    }
}

Test Code:

System.out.println(TestEnum.Test1.stringify(1.23f));
System.out.println(TestEnum.Test2.stringify(42));
System.out.println(TestEnum.Test3.stringify("foo"));
// but:
// System.out.println(TestEnum.Test1.stringify("foo")); // -> ClassCastException!

for (TestEnum test : TestEnum.values()) {
    for (Object input : new Object[]{1.23f, 42, "foo"}) {
        if (test.getInputType().isAssignableFrom(input.getClass())) {
            System.out.println(test.stringify(input));
        }
    }
}
记忆で 2024-10-05 20:32:56

您无法使用 enum 来做到这一点,但您可以使用泛型类来模拟此行为:

public abstract class TEST<T> {
    public static final TEST<Float> TEST1 = new TEST<Float>() {
        public String stringify (Float input){   
            return String.valueOf(input);   
        }
    };

    public abstract <T> String stringify(T input);
}

You can't do it with enums, but you can simulate this behaviour with generic class:

public abstract class TEST<T> {
    public static final TEST<Float> TEST1 = new TEST<Float>() {
        public String stringify (Float input){   
            return String.valueOf(input);   
        }
    };

    public abstract <T> String stringify(T input);
}
中性美 2024-10-05 20:32:56

你可以做到的。但尚不清楚有什么好处:

enum TEST {
    TEST1 {
        public <Float>String stringify(Float input) {
            System.out.println("TEST1");
            return String.valueOf(input);
        }
    },
    TEST2 {
        public <Integer>String stringify(Integer input) {
            System.out.println("TEST2");
            return String.valueOf(input);
        }
    },
    TEST3 {};
    public <T>String stringify(T input) {
        System.out.println("super");
        return "";
    }
    public <Integer>String stringify2(Object input) {
        System.out.println("non generic");
        return String.valueOf(input);
    }
}
public class Main{
    public static void main(String[] args) {
        for(TEST test:TEST.values()) {
            System.out.println(test.stringify(new Float(1.23)));
            System.out.println(test.stringify(new Integer(42)));
            System.out.println(test.stringify(new Double(4.56)));
        }
        for(TEST test:TEST.values()) {
            System.out.println(test.stringify2(new Float(1.23)));
            System.out.println(test.stringify2(new Integer(42)));
            System.out.println(test.stringify2(new Double(4.56)));
        }
    }
}

you can do it. but it's not clear what the benefit is:

enum TEST {
    TEST1 {
        public <Float>String stringify(Float input) {
            System.out.println("TEST1");
            return String.valueOf(input);
        }
    },
    TEST2 {
        public <Integer>String stringify(Integer input) {
            System.out.println("TEST2");
            return String.valueOf(input);
        }
    },
    TEST3 {};
    public <T>String stringify(T input) {
        System.out.println("super");
        return "";
    }
    public <Integer>String stringify2(Object input) {
        System.out.println("non generic");
        return String.valueOf(input);
    }
}
public class Main{
    public static void main(String[] args) {
        for(TEST test:TEST.values()) {
            System.out.println(test.stringify(new Float(1.23)));
            System.out.println(test.stringify(new Integer(42)));
            System.out.println(test.stringify(new Double(4.56)));
        }
        for(TEST test:TEST.values()) {
            System.out.println(test.stringify2(new Float(1.23)));
            System.out.println(test.stringify2(new Integer(42)));
            System.out.println(test.stringify2(new Double(4.56)));
        }
    }
}
南风几经秋 2024-10-05 20:32:56

将每个枚举值视为一个类。所以是的,枚举可以有方法,就像类一样 - 但它们都具有相同方法。

http://download.oracle.com/javase/tutorial/java/javaOO /enum.html

查看 Planet 示例。

另请注意,枚举本身可以有静态方法......(就像类一样)

Think of each Enum value as a class. So yes, the enums can have methods, just like a class does -- they all have the same methods though.

http://download.oracle.com/javase/tutorial/java/javaOO/enum.html

Look at the Planet example.

Also note that the enum itself can have static methods....(just like a class)

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