com.libfintech.libpay_sdk.util.EnumUtil Maven / Gradle / Ivy
The newest version!
package com.libfintech.libpay_sdk.util;
/**
* 枚举工具类
* Created by liamjung on 2018/8/7.
*/
public final class EnumUtil {
/**
* 解析枚举
*
* @param value 枚举取值
* @param enumCls 枚举类
* @param 枚举类泛型
* @return 枚举对象
*/
public static E parse(Object value, Class enumCls) {
E e = null;
try {
E[] eArr = (E[]) enumCls.getMethod("values").invoke(null);
for (E tempE : eArr) {
Object v = enumCls.getMethod("value").invoke(tempE);
if (v.equals(value))
e = tempE;
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
return e;
}
/**
* 转格式化字符串
*
* @param enumCls 枚举类
* @param 枚举类泛型
* @return 枚举对象
*/
public static String toFormattedString(Class enumCls) {
StringBuilder sb = new StringBuilder("[");
try {
E[] eArr = (E[]) enumCls.getMethod("values").invoke(null);
for (E tempE : eArr) {
String name = (String) enumCls.getSuperclass().getMethod("name").invoke(tempE);
Object value = enumCls.getMethod("value").invoke(tempE);
sb.append(name + "(" + (value instanceof String ? ("\"" + value + "\"") : value) + "), ");
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
//删除尾部空格
sb.deleteCharAt(sb.length() - 1);
//删除尾部逗号
sb.deleteCharAt(sb.length() - 1);
sb.append("]");
return sb.toString();
}
}