简体   繁体   English

在Java中将Enum类型值作为参数传递

[英]Pass Enum type value as a parameter in Java

I know I can check whether a String is contained in a specific Enum using the concept described by pseudo code below(I know there's no contains method for Enum , that's just for my example) : 我知道我可以使用下面的伪代码描述的概念来检查特定的Enum中是否包含字符串(我知道Enum没有contains方法,仅用于我的示例):

Enum Animal {
    Dog,
    Cat,
    Human
}

public boolean CheckAnimalValid(String name){
    return Animal.contains(name)? true : false;
}

But in previous way I need to implement the CheckValid method for each Enum class, since I need to know WHICH Enum class should I to check. 但是以以前的方式,我需要为每个Enum类实现CheckValid方法,因为我需要知道应该检查WHICH Enum类。

I want to know is there any method to pass Enum type as a parameter to a function, so that I can do in this way: 我想知道是否有任何方法可以将Enum类型作为参数传递给函数,这样我就可以这样做:

Enum Animal {
        Dog,
        Cat,
        Person
    }

Enum Plant {
    Grass,
    Flower,
    Tree
}

public boolean CheckEnumValid(String name, what_should_I_do? enum){
    return enum.contains(name)? true : false;
}

I want to know which type(or keyword) should I use in what_should_I_do? 我想知道在what_should_I_do中应该使用哪种类型(或关键字) in the previous code. 在前面的代码中。 I know I should use Generics, but I don't know how to do. 我知道我应该使用泛型,但我不知道该怎么做。 Thanks! 谢谢!

You can use the static method Enum.valueOf(Class<T> enumType, String name) which returns an enum of type T , if the name matches an enum constants of that type. 您可以使用静态方法Enum.valueOf(Class<T> enumType, String name) ,如果该名称与该类型的枚举常量匹配,则该方法返回类型T的枚举。 Otherwise is throws an IllegalArgumentException . 否则抛出IllegalArgumentException

Example usage: 用法示例:

Enum.valueOf(Plant.class, "Flower");

Wrapped in a method that returns a boolean: 包装在返回布尔值的方法中:

public <T extends Enum<T>> boolean checkValid(Class<T> enumType, String name){
    try {
        Enum.valueOf(enumType, name);
        return true;
    } catch(IllegalArgumentException e) {
        return false;
    }
}

Not certain if I fully understand your need but I suspect you want to lookuup in any enum by String - if that is the case then there are several ways to do this. 不确定我是否完全理解您的需求,但我怀疑您是否想在String中的任何 enum查找-如果是这种情况,那么可以通过多种方法进行。

First - let's define what you are looking for - something like this? 首先-让我们定义您要寻找的东西-这样的东西?

interface Lookup<S,T> {
    T lookup(S s);
}

Now you could adjust every enum to do something like this: 现在您可以调整每个enum以执行以下操作:

enum Animal implements Lookup<String,Animal>{
    Dog,
    Cat,
    Person;
    Map<String,Animal> lookup = Arrays.stream(Animal.values())
            .collect(Collectors.toMap(e -> e.name(), e -> e));
    public Animal lookup(String name) {
        return lookup.get(name);
    }
}

But I suspect you want to do this without hacking all of your enums - which would be a pain. 但是我怀疑您想这样做而不破坏所有 enums -这将是一件痛苦的事情。 Here's one method using a helper object. 这是使用辅助对象的一种方法。

class EnumLookup<E extends Enum<E>> implements Lookup<String,E> {
    final Map<String,E> lookup;

    public EnumLookup(Class<E> clazz) {
        lookup = Arrays.stream(clazz.getEnumConstants())
                .collect(Collectors.toMap(e -> e.name(), e -> e));
    }

    @Override
    public E lookup(String s) {
        return lookup.get(s);
    }
}

Now you can create one of these to interrogate the enum whenever you like. 现在,您可以创建其中之一来随时查询enum

enum Plant {
    Grass,
    Flower,
    Tree;
}

public void test() {
    EnumLookup<Plant> lookup = new EnumLookup<>(Plant.class);
    System.out.println("Tree -> "+lookup.lookup("Tree"));
}

It would be nice if you implement a generic method instead, java allows using contrains so you can for sure PASS ONLY AN ENUM, and thanks to interfaces you can restrict at compiling time what enums are allowed or not: 如果您改为实现通用方法,那就太好了,java允许使用禁忌症,因此可以确保只通过枚举,并且由于有了接口,您可以在编译时限制允许或不允许的枚举:

Define this generic method 定义此通用方法

public <T extends Enum<?> & ITag> void printEnum(T d) {
        System.out.println(d.name());
    }

define a tag interface: 定义标签接口:

interface ITag {
}

now you can Tag the enums that only valid in the method: 现在,您可以标记仅在方法中有效的枚举:

enum Color implements ITag {
    RED, GREEN, BLUE
}

enum STATE {
    ON, OFF
}

enum CONNECTION {
    UDP, TCP
}

as result, you can check if a method is taking the correct param at compiling time... 结果,您可以在编译时检查方法是否采用了正确的参数...

 printEnum(Color.GREEN); //valid
 printEnum(STATE.OFF);// invalid The method printEnum(T)... is not applicable for the arguments..
 printEnum(CONNECTION.UDP);// invalid The method printEnum(T)... is not applicable for the arguments..
 printEnum("Green"); // invalid The method printEnum(T)... is not applicable for the arguments..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM