tags:

views:

31

answers:

2

I have a set of data which needs to be imported from a excel sheet, lets take the simplest example. Note: the data might eventually support uploading any locale.

e.g. assuming one of the fields denoting a user is gender mapped to an enumeration and stored in the database as 0 for male and 1 for female. 0 and 1 being short values.

If I have to import the values I cannot expect the user to punch in numbers (since they are not intuitive and is cumbersome when the enumerations are bigger), what would be the correct way to map to enumerations.

Should we ask them to provide a string value in these cases (e.g. male or female) and provide the transformation to a enum in our code by wring a method public static Gender Gender.fromString(String value)

A: 

Providing a static method looks fine to me. Then you have one single point in your application where you care about the transformation from the user input to the Gender object.

As you mentioned localization, a second method

public static Gender Gender.fromString(String value, Locale locale);

could be a good idea.

Andreas_D
+2  A: 

You don't need to write a fromString; enum types already have a static valueOf(String):

public class EnumValueOf {
    enum Gender {
        MALE, FEMALE;
    }
    public static void main(String[] args) {
        Gender g = Gender.valueOf("MALE");
        System.out.println(g);
        // prints "MALE"
        System.out.println(g == Gender.MALE);
        // prints "true"
    }
}

The specification

It's somewhat hidden, but this is specified in JLS.

JLS 8.9 Enums

In addition, if E is the name of an enum type, then that type has the following implicitly declared static methods:

/**

* Returns an array containing the constants of this enum 
* type, in the order they're declared.  This method may be
* used to iterate over the constants as follows:
*
*    for(E c : E.values())
*        System.out.println(c);
*
* @return an array containing the constants of this enum 
* type, in the order they're declared
*/
public static E[] values();

/**
* Returns the enum constant of this type with the specified
* name.
* The string must match exactly an identifier used to declare
* an enum constant in this type.  (Extraneous whitespace 
* characters are not permitted.)
* 
* @return the enum constant with the specified name
* @throws IllegalArgumentException if this enum type has no
* constant with the specified name
*/
public static E valueOf(String name);
polygenelubricants