Im working on java, I have created an enum as follows:
public enum myEnum
{
india,
russian,
england,
north America
}
Above
public enum myEnum
{
india,
russian,
england,
north_america
}
To access values
myEnum.values()
The Java naming rule does not allow white spaces as possible characters in a name of variables, classes, enums and enum members (and every other identifier). Therefore this "problem" cannot be resolved. Just use `north_america' as member name!
An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter.
The Java letters include uppercase and lowercase ASCII Latin letters A-Z (\u0041-\u005a), and a-z (\u0061-\u007a), and, for historical reasons, the ASCII underscore (_, or \u005f) and dollar sign ($, or \u0024). The $ character should be used only in mechanically generated source code or, rarely, to access preexisting names on legacy systems.
The "Java digits" include the ASCII digits 0-9 (\u0030-\u0039).
Write them together like northAmerica
or use an underscore north_America
.
The problem has nothing (specifically) to do with enums: in Java, names can't have spaces. Try eliminating the space (using capitalization to tell the bits apart) or use underscores instead.
just make your own valueOf like function in your enum class. Replace spaces with underscores. name your enum constants like this "north_america("North America")". If the method fails to find your enum it just returns the parameter.
public static String valueOfOrDefault(String myValue) {
//replace space with underscore so it matches enum name
String value=myValue.toUpperCase().replaceAll("\\s", "_");
for(myEnum type : myEnum.class.getEnumConstants()) {
if(type.name().equalsIgnoreCase(value)) {
return type.toString();
}
}
return myValue;
}
I also introduced an own valueOf method. But I return with the Enum Type and I do not have to convert the "checkString"
checkString is "Petty Cash" for example.
JournalType journalType = JournalType.valueOfOrDefault(checkString);
public enum JournalType {
MISC_BILLING("Misc Billing"),
MISC_BILLING_AUTONUM("Misc Billing AutoNum"),
PRETTY_CASH("Petty Cash"),
RECURRING_AP("Recurring AP"),
GL_JOURNAL("GL Journal"),
GDS_NDS("GDS/NDS");
private final String journalType;
JournalType(String journalType) {
this.journalType = journalType;
}
@Override
public String toString() {
return journalType;
}
public static JournalType valueOfOrDefault(String myValue) {
for(JournalType type : JournalType.class.getEnumConstants()) {
if(type.toString().equals(myValue)) {
return type;
}
}
throw new IllegalArgumentException("JournalType not found");
}
}