Enumerate conversion tools
Package Com.util;import Java.lang.reflect.method;import Java.util.linkedhashmap;import java.util.Map;import org.apache.commons.lang3.reflect.methodutils;/** * <strong> function:</strong> enumeration using tools * <strong></ Strong>gary Huang * <strong> date:</strong> 2014-3-5 * <strong> copyright:<strong> All rights reserved (C) 2014,qq 834865081 */public class Enumutil {public static String GetText (class<?> ref, Object code) {return Parseenum (ref). GE T (transformutils.tostring (code)); }public static <T> map<string, string> parseenum (class<t> ref) {map<string, string> Map = new Link Edhashmap<string, string> (); if (Ref.isenum ()) {t[] ts = ref.getenumconstants (); for (t t:ts) {String text = Getinvokevalue (T, "GetText"); Enum<?> tempenum = (enum<?>) t; if (text = = null) {text = Tempenum.name ();} String code = Getinvokevalue (T, "GetCode"); if (code = = NULL) {code = transformutils.tostring (Tempenum.ordinal ());} Map.put (code, text); }}return Map;} public static <T> T Getenumitem (class<t> ref, Object i) {T returnt = null; if (Ref.isenum ()) {t[] ts = ref.gete Numconstants (); String tempi = Helper.checknull (i); for (T t:ts) {enum<?> tempenum = (enum<?>) T; String code = Getinvokevalue (T, "GetCode"); if (code = = NULL) {code = transformutils.tostring (Tempenum.ordinal ());} if (tempi.equals (code)) {returnt = t; break;}}} return returnt; }static <T> string Getinvokevalue (T T, string MethodName) {Method method = Methodutils.getaccessiblemethod (T.GETCL (), methodName); if (Null = = method) {return null;} try {String text = transformutils.tostring (Method.invoke (t)); return text;} catch (Exception e) {return null;}}Defining enumerations
public enum Yes {A (0), B (1), C (2), D (3), F (4);p rivate Integer code; Yes () {}yes (int code) {this.code = code;} Public Integer GetCode () {return code;}}
Enumeration of applications
public static void Main (string[] args) {System.out.println (Enumutil.gettext (Yes.class, 2)); /* Get the textual content of enumeration 2 */system.out.println (Enumutil.getenumitem (Yes.class, 2)); /* Converts the number 2 to an enumeration */system.out.println (Enumutil.parseenum (Yes.class)); /* Convert an enumeration to map*/}