Java Enum bean object conversion Utilities
- method#1 - use the generic DescriptiveEnumObject as a receiver, then use EnumObjectUtils to do the conversion
- example:
class Test { public static void main(String[] args){ DescriptiveEnumObject<SexEnum, Character> sexEnum = EnumObjectUtils.asDescriptiveEnumObject(DescriptiveEnumObject.class, SexEnum.FEMALE); System.out.println(String.format("sex enum = %s", gson.toJson(sexEnum))); } }
- method#2 - inherit DescriptiveEnumObject and convert directly from EnumObjectUtils
- example:
// === enum class ... === public enum SexEnum implements IDescriptiveEnum<Character> { MALE('M', "male"), FEMALE('F', "FEMALE"); SexEnum(char code, String description) { // implement enum ... } } // === enum object class === class SexEnumObject extends DescriptiveEnumObject<SexEnum, Character> { // implement constructor ... public SexEnumObject(SexEnum enumInstance) { super(enumInstance); } } // === usage === public class TestMain { public static void main(String[] args) { Gson gson = new Gson(); SexEnumObject mSexObj = EnumObjectUtils.asDescriptiveEnumObject(SexEnumObject.class, SexEnum.MALE); System.out.println("sex = "+gson.toJson(mSexOb)); } }
- Get enum by specifying code
- example:
// === usage === public class TestMain { public static void main(String[] args) { SexEnum mSex = EnumObjectUtils.getByCode(SexEnum.class, "M"); } }
- List all possible values to EnumObject List
- example:
// === usage === public class TestMain { public static void main(String[] args) { List<SexEnumObject> sexEnumObjList = EnumObjectUtils.asDescriptiveEnumObjectList(SexEnum.class, SexEnumObject.class); System.out.println(String.format("SexEnum.values() as obj list = %s", gson.toJson(sexEnumObjList))); } }
- List all possible values as EnumObject Map
- example:
// === usage === public class TestMain { public static void main(String[] args) { Map<Character, SexEnumObject> sexEnumObjMap = EnumObjectUtils.asDescriptiveEnumObjectMap(SexEnum.class, SexEnumObject.class); System.out.println(String.format("SexEnum.values() as obj map = %s", gson.toJson(sexEnumObjMap))); } }