Dolphin
Dolphin

Reputation: 38631

How to get enum by user defined name in java?

I am defined a enum in Java 8 like this:

public enum Cflb implements IBaseEnum {        
    没收违法所得("没收违法所得、没收非法财物", 2),
    暂扣或者吊销许可证("暂扣或者吊销许可证、暂扣或者吊销执照", 4);
    private String name;
    private int value;

    public void setName(String name) {
        this.name = name;
    }

    public void setValue(int value) {
        this.value = value;
    }

    Cflb(String name, int value) {
        this.name = name;
        this.value = value;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public int getValue() {
        return value;
    }  
}

How to get enumn by "暂扣或者吊销许可证、暂扣或者吊销执照"? attention:not get the enumn by value. The code maybe like this:

Cflb cflb = getEnumnByInternalName("暂扣或者吊销许可证、暂扣或者吊销执照");

Upvotes: 0

Views: 66

Answers (1)

f1sh
f1sh

Reputation: 11934

Loop over the enum constants using values() and compare the name:

static Cflb getEnumnByInternalName(String iname) {
  for(Cbfl c : values()){
    if(c.name.equals(iname)){
      return c;
    }
  }
  return null; //or throw an Exception, whatever you need
}

Then you can use it like this:

Cflb cflb = Cflb.getEnumnByInternalName("暂扣或者吊销许可证、暂扣或者吊销执照");

And as @khelwood mention above: Remove the setters.

Upvotes: 3

Related Questions