English 中文(简体)
如何通过不同的圈套作为争论?
原标题:How to pass different enums as argument?
  • 时间:2012-05-28 02:50:29
  •  标签:
  • java
  • enums

我有一些各式各样的字符串, 我想创建一个函数, 如果字符串是字符串变量名称之一, 可以找到或不找到( 不清楚它是否真的可以理解 ) 。

enum MYENUM {
  ONE,
  TWO;
}

enum MYENUM1 {
  RED,
  GREEN;
}

我想这样做(这只是个例子,

if(isInEnum(MYENUM, "one")) ...
if(isInEnum(MYENUM1, "one")) ...

isinEnum 函数(代码不好,仅供理解):

boolean isinEnum(enum enumeration, String search) {
  for(enum en : enumeration.values()){
    if(en.name().equalsIgnoreCase(search)) return true;
  }
  return false;
}

这种事有可能吗?

根据我在网上所读到的,我想没有, 但也许有人有办法做到这一点, 而不是为每个大奖做一个循环。

最佳回答

这是用反省的方法...

public class EnumFinder {

    public static <T extends Enum<T>>  boolean isInEnum(Class<T> clazz, String name) {
        for (T e : clazz.getEnumConstants()) {
            if (e.name().equalsIgnoreCase(name)) {
                return true;
            }
        }

        return false;
    }

    public static void main(String[] argv) {
        System.out.println(isInEnum(MYENUM.class, "one"));   // true
        System.out.println(isInEnum(MYENUM1.class, "one"));  // false
    }
}

你对答案的尝试实际上非常接近。唯一的区别是爪哇需要一个定义类的例子来回答关于运行时未知型号的问题。

问题回答

这或许不是最干净的解决方案, 因为它在正常程序流程中使用例外, 但肯定很短, 因为它避免循环 :

boolean isinEnum(Class<T> enumClass, String search) {
    try {
        Enum.valueOf(enumClass, search);
        return true;
    } catch (IllegalArgumentException iae) {
        return false;
    }
}

你的问题很难理解 但我想我明白了

你可能让事情变得 对自己更艰难 比必要的。

查看 Java s 地图界面/ 数据结构( 以 java. util), 看看是否将您移动到接近解决方案的地方 :

java.util 界面映射图<K,V>

如果不是的话,你做过任何一腿工作,我再做一次,看看我是否能帮助你。-)





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签