how can I get enum value by name string

前端 未结 2 1555
情书的邮戳
情书的邮戳 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:44

    You can use something like:

    final Mobile mobile = Mobile.valueOf("Samsung");
    final int price = mobile.showPrice();
    

    (you do have to change the scope of the method showPrice() to public).

    0 讨论(0)
  • 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"));
    
    0 讨论(0)
提交回复
热议问题