I have an enum as follows:
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;
}
}
Now I am using google reflections library and have come up with a custom Annotation where I mark the enum above with an annotation like @makejson.
The idea is to scan on app startup using reflections for all classes with the @makejson annotation and then generate the json object for each of these enums.
What I’m trying to do is in the startup class:
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()));
}
}
}
This code breaks with the following exception: Exception in thread “main” java.lang.IllegalArgumentException: wrong number of arguments
Any help would be greatly appreciated. The end objective is to be able to get a json object for SomeType{SOME_KEY:”display-value”}. For this I am unable to get the value of the enum constant using Reflection.
So here’s what I ended up doing:
I modified the @makejson annotation to include a field called label which is mandatory and which should be set to the method that can return the description associated with SOME_KEY in the enum.
Here’s what the annotation looks like:
so the annotation at the enum declaration looks like
@makejson(label=”getLabel”)
public enum SomeType {
… // same as in the question above
}
Then in the parsing class, I simply get this method from the annotation’s method and invoke it for the correct constant:
So in the end I circumvented the issue of not being able to call the method using reflection by using annotation to plug this info in at runtime!