0

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("暂扣或者吊销许可证、暂扣或者吊销执照");
3
  • 4
    Loop through the enum elements until you find the one with the matching name. Commented Nov 29, 2018 at 10:14
  • 4
    By the way, it's unorthodox to have setters in an enum. Enums are generally expected to be fully constant. Commented Nov 29, 2018 at 10:15
  • What exactly is IBaseEnum? Is that a "real" Java enum? Or just a class that is called "enum"? Commented Nov 29, 2018 at 10:19

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you,I've solved the problem by your tips.@f1sh

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.