1

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 price;
  Mobile(int p) {
    price = p;
  }
  int showPrice() {
    return price;
  }
}

I can get the class name and the name string

Class enumClass = Class.forName("practice.Mobile");
String name = "Samsung";

how can I get the Samsung value 400 only use enumClass and name? thanks a lot

3
  • 1
    Do you mean like Enum.valueOf(String)? e.g Mobile.valueOf("Nokia") Commented May 15, 2017 at 3:18
  • 1
    Unrelated: Standard naming convention is for that method to be named getPrice(), not showPrice(), especially since the method doesn't actually show anything. Commented May 15, 2017 at 3:46
  • @Edwin yes, Enum,valueOf(enumClass, name), can we get name corresponding value 400 by this type method? Commented May 15, 2017 at 7:48

2 Answers 2

5

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).

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

2 Comments

Why the final keywords? Not required and does add zero value to the example.
@Gabe how about use variable enumClass? not mobile.
2

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"));

Comments

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.