0

I am reading from a database, which has values like "BUY" or "SELL" for Column "BUY_SELL"

In Java, I've made this attribute into an enum, called RequestType. In the code line below, I'm trying to set my entity attribute to the value I read from the database column, but I'm not sure how I can enter a string into an enum type.

There doesn't seem to be a resultset .method that is suitable for this

 req.setRequestType(rs.getString("BUY_SELL")); //The method setRequestType(RequestType) in the type Request is not applicable for the arguments (String)
stfudonny
  • 53
  • 1
  • 9
  • Possible duplicate of [Lookup enum by string value](http://stackoverflow.com/questions/604424/lookup-enum-by-string-value) – AdamSkywalker May 11 '16 at 16:15

2 Answers2

0

Try

RequestType reqType = RequestType.valueOf(rs.getString("BUY_SELL"));
req.setRequestType(reqType);

I am assuming BUY and SELL exist as valid values for the Enum, i.e.:

public enum RequestType { BUY, SELL }
Paul
  • 3,009
  • 16
  • 33
0

You can change your enum as :

public enum RequestTypeEnum {
    BUY("BUY"), SELL("SELL"),BUY_SELL("BUY_SELL");

  private String text;

  RequestTypeEnum(String text) {
    this.text = text;
  }

  public String getText() {
    return this.text;
  }
  public static RequestTypeEnum fromString(String text) {
    if (text != null) {
      for (RequestTypeEnum req : RequestTypeEnum.values()) {
        if (text.equalsIgnoreCase(req.text)) {
          return req;
        }
      }
    }
    throw new RuntimeException("Invalid String!!");
  }
}
sauumum
  • 1,638
  • 1
  • 19
  • 36
  • 1
    I think this is reinventing the wheel. Any Java `Enum` automatically has a `name()` and `valueOf()` more or less equivalent to your `getText()` and `fromString()`. If you want a more lenient `fromString()` (say for trimming or case insensitivity) you can implement it as a static utility method that will work for *any* Enum class. – Paul May 11 '16 at 16:35