不知道你想能走多远,但这里是一些非常丑陋的代码是你的枚举的创伤更小:
的所有代码不能编译
public class Main {
public enum IpHdrProtocol {
TCP(6), SCTP(132), MPLS(137);
int Value;
IpHdrProtocol(int value) {
Value = value;
}
}
public static void main(String[] argv) throws NoSuchMethodException, IllegalArgumentException, InvocationTargetException,
IllegalAccessException, SecurityException, NoSuchFieldException {
System.err.println(getProtocol(6));
System.err.println(getProtocol(132));
System.err.println(getProtocol(137));
}
private static IpHdrProtocol getProtocol(int i) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException,
SecurityException, NoSuchFieldException {
Field f = IpHdrProtocol.class.getDeclaredField("Value");
Method m = IpHdrProtocol.class.getMethod("values", null);
Object[] invoke = (Object[]) m.invoke(null, null);
for (Object o : invoke) {
if (!f.isAccessible()) {
f.setAccessible(true);
}
if (((Integer) f.get(o)).intValue() == i) {
return (IpHdrProtocol) o;
}
}
return null;
}
}
这就是我想要的并基于此实现了一个解决方案。实际上,我首先创建了一个反序列化程序对象,它查询了您所显示的枚举类,但创建了一个整数值和相应的枚举实例值的映射。当我使用它来反序列化时,我只需在地图上查找。 Simples。所有被问及特定枚举类的问题都是它实现了一个支持getIntValue()的简单接口,这非常干净。 – 2012-03-07 13:55:11