Enable Enum when lines contain dashes

I would like to use enumeration as a way of switching strings, however java complains because my string contains a "-". As you can see from the code below, where IC19-01 and IC19-02 contain "-".

public class CMain { public enum Model { IC19-01, IC19-02 } public static void main(String[] args){ String st = "IC19-01"; switch (Model.valueOf(st)) { case IC19-01: System.out.println("Case IC19-01"); break; } } } 

What can I do for this?

+4
source share
3 answers

This is not possible for Java, because each element must be a valid identifier (and valid Java identifiers may not contain dashes).

+4
source

This is not possible in Java as it is. But you can do your own implementation as work, although it will give more code. You can change your enum as follows:

  public enum Model { IC19_01("IC19-01"), IC19_02("IC19-02") private final String name; private Model(String name){ this.name = name; } public String getName(){ return name; } public static Model getByName(String aName){ for(Model current: Model.values()){ if(current.getName().equalsIgnoreCase(aName.trim())){ return current; } } return null; } } 

Then you can call Model.getByName(st) instead of Model.valueOf . Alternatively, in Java 7 you can switch the actual String .

+2
source

Blockquote

Enumerations are classes and must follow conventions for classes. Enumeration instances are constants and must follow conventions for constants.

Blockquote

Details on this can be found at the following link.

Coding Conventions - Name Enumeration> Hope this helps.

0
source

All Articles