Re: [Switch()...case]From String to enum
Roedy Green wrote:
On Mon, 14 Jan 2008 18:45:36 +0100, Daniel Moyne <dmoyne@tiscali.fr>
wrote, quoted or indirectly quoted someone who said :
What you mean by override valueOf() : create a new method of this name in
class myMenuEnum that would provide what I expect ; I will try to work out
this idea.
it is a static, so you can't literally override it. You might as well
give it a slightly different name to make it clear what you are doing
e.g. valueOfAlias( ).
Ah, corrected I am, thanks ;) To appease the Usenet gods, I shall post
an abbreviated example of how I implemented an enum. It also uses
ResourceBundels to get display values in the current locale.
/**
* Enum class for support types in this application.
* @author Sabine Dinis Blochberger
*/
public enum SupportTypes {
COMMERCIAL ("comercial", "ds_commercial"),
TECHNICAL ("tecnico", "ds_technical"),
NONE ("nenhum", "ds_none");
private final String supportName;
private final String displayName;
SupportTypes(String supportName, String displayName) {
this.supportName = supportName;
this.displayName = displayName;
}
public String supportName() { return supportName; }
public String displayName() {
return java.util.ResourceBundle.getBundle(
"resources/displayStrings").getString(
this.displayName);
}
@Override
public String toString() { return supportName; }
/** Returns the enum corresponding to a name.
* @param name support type name
* @return support type enum */
public static SupportTypes supportTypeOf(final String name) {
if (name == null || name.isEmpty()) return NONE;
try {
if (name.equalsIgnoreCase(COMERCIAL.displayName()) ||
name.equalsIgnoreCase(COMERCIAL.supportName))
return COMERCIAL;
if (name.equalsIgnoreCase(TECNICAL.displayName()) ||
name.equalsIgnoreCase(TECNICAL.supportName))
return TECNICAL;
if (name.equalsIgnoreCase(NONE.displayName()) ||
name.equalsIgnoreCase(NONE.supportName))
return NONE;
return valueOf(name); // last try
} catch (Exception ex) {
return NONE; // default value
}
}
};
The intersting bit to the OP is the method supportTypeOf().
--
Sabine Dinis Blochberger
Op3racional
www.op3racional.eu