我有一个枚举如下:
public enum SomeType {
SOME_KEY (some-display-value-as-label);
private String label;
private SomeType(String label){
this.label=label;
}
public String getLabel() {
return label;
}
public void setLabel(String value) {
this.label = value;
}
}
现在我正在使用谷歌反射库,并提出了一个自定义注释,我在上面用 @makejson 之类的注释标记了枚举。
想法是在应用程序启动时使用反射扫描所有带有@makejson 注释的类,然后为每个枚举生成 json 对象。
我正在尝试做的是在启动类中:
Reflections reflections = new Reflections("my.package.name");
Set<Class<?>> annotatedClasses = reflections.getTypesAnnotatedWith(MakeJson.class);
for (Class<?> annotated : annotatedClasses) {
if (annotated.isEnum()) {
MakeJson j = annotated.getAnnotation(MakeJson.class);
Object[] constants = annotated.getEnumConstants();
Method[] methods = annotated.getMethods();
Method getValue = null;
for (Method m : methods) {
if ("valueOf".equals(m.getName())) {
getValue = m; //get Reference of valueOf method
break;
}
}
//List<Object> labels = Arrays.asList(m.invokem.getReturnType().isEnum()(annotated));
for (Object constant : constants) {
System.out.println(constant.toString());
System.out.println(getValue.invoke(annotated,constant.toString()));
}
}
}
此代码因以下异常而中断:线程“主”java.lang.IllegalArgumentException 中的异常:参数数量错误
如有任何帮助,我们将不胜感激。最终目标是能够获得 SomeType{SOME_KEY:"display-value"} 的 json 对象。为此,我无法使用反射获取枚举常量的值。
最佳答案
我之前的回答是错误的。这里发生的是 Enum 类定义了一个 public static valueOf(Class<?>, String)
。方法。当 java 编译器转换你的 enum SomeType
时进入一个类,它会生成一个 public class SomeType extends Enum<SomeType>
, 并将添加另一个 valueOf(String)
SomeType
的方法类(class)。因此,您最终在类中得到两个 方法,称为“valueOf”。在我看来,您实际上是在调用 valueOf(Class, String)
, 但真的打算打电话 valueOf(String)
要解决该问题,请将循环从:
Method[] methods = annotated.getMethods();
Method getValue = null;
for (Method m : methods) {
if ("valueOf".equals(m.getName())) {
getValue = m; //get Reference of valueOf method
break;
}
}
到
Method getValue = annotated.getMethod("valueOf", new Class<?>[]{String.class});
然后您的问题应该得到解决。
关于java - 如何在运行时将 Java Enum 转换为 Json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12782278/