java 如何将方法参数声明为任何枚举

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11435067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 05:06:53  来源:igfitidea点击:

How to declare a method parameter as any enum

javagenericsenums

提问by popcoder

I have a method on which I need to pass an enum as a parameter.

我有一个方法,我需要将枚举作为参数传递给它。

public <T> T doSomething(SomeEnum operation, Class<T> something);

I have several enums and the method is a common one which should work with any enums. What is the correct way to write this method signature to accept any generic enum types? I know that I can use a marker interface to this purpose, but I would like to write it with generic enum signatures. Please advise me on this.

我有几个枚举,该方法是一个通用的,应该适用于任何枚举。编写此方法签名以接受任何通用枚举类型的正确方法是什么?我知道我可以为此目的使用标记接口,但我想用通用枚举签名来编写它。请就此给我建议。

Whats the bad idea with the below one: (It works but I get warnings from IDE saying it is a raw type. I'm not clear about the reason).

下面的一个坏主意是什么:(它有效,但我收到来自 IDE 的警告,说它是原始类型。我不清楚原因)。

 public void doSomething(Enum operation);

回答by Istvan Devai

public <E extends Enum<E>> void doSomething(E operation);

EDIT: An example according to your modifications:

编辑:根据您的修改示例:

public class Main {

    public enum Day {
        SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
        THURSDAY, FRIDAY, SATURDAY 
    }

    public <E extends Enum<E>> E doSomething(E operation, Class<E> klazz) {

        return operation;
    }

    public static void main(String[] args) {

        new Main().doSomething(Day.FRIDAY, Day.class);
    }

}

EDIT2:

编辑2:

if you need T and the Enum as separate types, then you'll need:

如果您需要 T 和 Enum 作为单独的类型,那么您将需要:

public <T, E extends Enum<E>> T doSomething(E operation, Class<T> klazz) {

回答by Reverend Gonzo

You could do:

你可以这样做:

public void doSomething(final Enum<?> operation);

which says it needs to be an enum, but not any specific one.

它说它需要是一个枚举,但不是任何特定的枚举。

回答by Ahmed Gamal

This one is more cleared :

这个更清楚:

    public class EnumTest {

    protected static <E extends Enum<E>> void enumValues(Class<E> enumData) {
        for (Enum<E> enumVal: enumData.getEnumConstants()) {  
            System.out.println(enumVal.toString());
        }  
    }

    public static enum TestEnum {
        ONE, TWO, THREE;
    }

    public static void main(String param [] ) {
        EnumTest.enumValues(EnumTest.TestEnum.class);
    }
}