English 中文(简体)
原标题:How to pass different enums as argument?
  • 时间:2012-05-28 02:50:29
  •  标签:
  • java
  • enums

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

enum MYENUM {

enum MYENUM1 {


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