如何将方法参数声明为任何枚举 [英] How to declare a method parameter as any enum

查看:111
本文介绍了如何将方法参数声明为任何枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

下面的一个坏主意是什么:(它可以工作,但是我从IDE收到警告,说它是原始类型。我不清楚原因)。

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).

 public void doSomething(Enum operation);


推荐答案

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:

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

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

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

这篇关于如何将方法参数声明为任何枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆