选择正确的枚举

时间:2011-09-01 14:10:48

标签: java variables enums

我有许多枚举,每个枚举都包含要测试的属性的名称。我遇到的问题是如何为对象选择相关的枚举。如何定义一个在整个代码中使用的Enum变量,可以通过初始化方法设置。

编辑:

抱歉延迟回复。我不得不离开办公桌

这很糟糕的设计。我有几个枚举如下:

public enum AccountGrpEnum {
    Account("Account"),
    AccountType("AccountType"),
    AcctIDSource("AcctIDSource");

    private static Set<String> grpNames = new HashSet<String>(3) {{       
        for(AccountGrpEnum e : AccountGrpEnum.values()) {          
            add(e.toString());       
        }     
    }}; 

    public static boolean contains(String name) {       
        return grpNames.contains(name);     
    } 

    private String name;

    private AccountGrpEnum(String name) {
        this.name = name;
    }

    public String toString() {
        return this.name;
    }

}

另一个Enum

public enum BlockManValEnum {

    avgPx("avgPx"),
    quantity("quantity"),
    securityIDSource("securityIDSource"),
    securityID("securityID"),
    blockStatus("blockStatus"),
    side("side");

    private static Set<String> names = new HashSet<String>(9) {{       
        for(BlockManValEnum e : BlockManValEnum.values()) {          
            add(e.toString());       
        }     
    }}; 

    public static boolean contains(String name) {       
        return names.contains(name);     
    } 

    private String name;

    private BlockManValEnum(String name) {
        this.name = name;
    }

    public String toString() {
        return this.name;
    }

}

在我的代码中,我正在检查传入对象的字段,以查看它们是否包含在Enum中。如下:

if (BlockManValEnum.contains(fields[i].getName()))

但我希望它符合

的要求
if (variableEnum.contains(fields[i].getName()))

可以在运行时设置variableEnum

希望这是更清晰的家伙

3 个答案:

答案 0 :(得分:2)

以先前的答案为基础。

enum Color {
    RED(1),
    GREEN(2),
    BLUE(3);

    int attrib;

    Color(int attribValue) {
        attrib = attribValue;
    }

    public Color getColorForAttrib(int attribValue) {
        for(Color c : Color.values()) {
            if(c.attrib == attribValue) {
                return c;
            }
        }
        throw new IllegalArgumentException("No color could be found for attrib of value " + attribValue);
    }
}

...


class SomeClass {
    Color c;
    public void SomeClass(Color c) {
        this.c = c;
    }
 }

...

class SomeClassUser {
    public static void main(String[] args) {
        Color c = Color.getColorForAttrib(Integer.valueOf(args[i]));
        new SomeClass(c);
    }
}

请记住,简单地说,枚举只是一个类,因此您可以添加任何您想要的方法。这是否是一个好主意取决于环境

答案 1 :(得分:1)

使用Enum.valueOf

Enum<?> variableEnum = AccountGrpEnum.class;
if(Enum.valueOf(variableEnum.getClass(), field[i].getName()) != null) {
   doSomething();
}

答案 2 :(得分:0)

由于枚举类,因此可以实现接口,你可以创建一个包含contains()方法的接口,然后在你的枚举上实现该方法,然后使用一种泛型方法,它接受实现该接口的特定枚举类型的类令牌(并且可以在运行时设置)进行测试。像这样:

<强> CanBeTestedForContains:

public interface CanBeTestedForContains {
  boolean contains(String name);
}

<强> ColorEnum:

import java.util.HashSet;
import java.util.Set;

public enum ColorEnum implements CanBeTestedForContains {
  R("red"),
  B("blue");

  private static Set<String> names = new HashSet<String>(3) {
    {
      for (final ColorEnum e : ColorEnum.values()) {
        add(e.name);
      }
    }
  };

  private String name;

  private ColorEnum(final String name) {
    this.name = name;
  }

  @Override
  public boolean contains(final String name) {
    return names.contains(name);
  }
}

<强> SuitEnum:

import java.util.HashSet;
import java.util.Set;

public enum SuitEnum implements CanBeTestedForContains {
  D("diamonds"),
  H("hearts"),
  C("clubs"),
  S("spades");

  private static Set<String> names = new HashSet<String>(3) {
    {
      for (final SuitEnum e : SuitEnum.values()) {
        add(e.name);
      }
    }
  };

  private String name;

  private SuitEnum(final String name) {
    this.name = name;
  }

  @Override
  public boolean contains(final String name) {
    return names.contains(name);
      }
}

<强> ContainsSelectorTest:

public class ContainsSelectorTest {
  private static <E extends Enum<E> & CanBeTestedForContains> boolean contains(final Class<E> enumClass, final String name) {
    return enumClass.getEnumConstants()[0].contains(name);
  }

  public static void main(final String[] args) {
    if (contains(ColorEnum.class, "red")) {
      System.out.printf("%s contains %s\n", ColorEnum.class, "red");
    }

    if (contains(SuitEnum.class, "hearts")) {
      System.out.printf("%s contains %s\n", SuitEnum.class, "hearts");
    }

    if (contains(SuitEnum.class, "red")) {
      System.out.println("This shouldn't happen.");
    } else {
      System.out.printf("%s DOES NOT contain %s\n", SuitEnum.class, "red");
    }
  }
}

<强>输出:

  

类ColorEnum包含红色

     

class SuitEnum包含心类

     

class SuitEnum不包含红色