Enum serializaition and deserialization


/ Published in: Java
Save to your folder(s)

//Sample use
String dbVal = getSerializedForm(Suit.SPADE);

// save dbVal to db in larger insert/update ...
Suit suit = deserialize(Suit.class, dbVal);

*Credit: Dov Wasserman*


Copy this code and paste it in your HTML
  1. public static String getSerializedForm(Enum<?> enumVal) {
  2. String name = enumVal.name();
  3. // possibly quote value?
  4. return name;
  5. }
  6.  
  7. public static <E extends Enum<E>> E deserialize(Class<E> enumType, String dbVal) {
  8. // possibly handle unknown values, below throws IllegalArgEx
  9. return Enum.valueOf(enumType, dbVal.trim());
  10. }

URL: http://stackoverflow.com/questions/229856/ways-to-save-enums-in-database/230756#230756

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.