how can I get enum value by name string

前端 未结 2 1582
情书的邮戳
情书的邮戳 2021-01-25 17:21

I want to get the enum value by name string,

this the enum code: package practice;

enum Mobile {
  Samsung(400),
  Nokia(250),
  Motorola(325);

  int pr         


        
2条回答
  •  既然无缘
    2021-01-25 17:46

    as you may know, there is a valueOf method in every enum, which returns the constant just by resolving the name(read about exceptions when the string is invalid.)

    now, since your enum has another fields associated to the constants you need to search its value by matching those fields too...

    this is a possible solution using

    java 8

    public enum ProgramOfStudy {
        ComputerScience("CS"), 
        AutomotiveComputerScience("ACS"), 
        BusinessInformatics("BI");
    
        public final String shortCut;
    
        ProgramOfStudy(String shortCut) {
            this.shortCut = shortCut;
        }
    
        public static ProgramOfStudy getByShortCut(String shortCut) {
    
            return Arrays.stream(ProgramOfStudy.values()).filter(v -> v.shortCut.equals(shortCut)).findAny().orElse(null);
        }
    }
    

    so you can "resolve" the enum by searching its "shortcut"

    like

    System.out.println(ProgramOfStudy.getByShortCut("CS"));
    

提交回复
热议问题