Posted By

jasonseney on 10/13/09


Tagged

enum


Versions (?)

Enum serializaition and deserialization


 / Published in: Java
 

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

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

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

Credit: Dov Wasserman

  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. }

Report this snippet  

You need to login to post a comment.