I have a map they key of the map is an enum and has some values.
I have a java class with fields, the fields are annotated with the enum values, now i want to set the values from the map to the fields, any suggestions,idea how to go about it?
I am using plain old reflection, but is there a better way to achieve this , something in spring or some thing from apache commons etc?
eg
Map<Myenum,String> map = new HashMap<Myenum,String();
map.add(Myenum.Value1, "1");
map.add(Myenum.Value2, "2");
map.add(Myenum.Value3,"3");
i have a java class like
MyClass{
@Use(fieldName=Myenum.Value1)
String Field1;
@Use(fieldName=Myenum.Value2)
String Field2;
@Use(fieldName=Myenum.Value3)
Object Field3;
@Use(fieldName=Myenum.Value4)
Integer Field4;
}
what i want to MyClass class to be created and fields(Field1,Field2,Field3, Field4 ) to loaded with values from the map with keys matching the annotation on the fields.
eg field1 should have vaule 1 becuase the annotation of field1 matches the key for the entry 1 in the map.
May be something similar to how Jaxws @XMLElement annotated fields gets the value loaded from an xml/soap
Any suggestions?
I don't know if Spring has a custom interceptor/handler for custom annotations. You can do this pretty easily with basic reflection.
Map
. Class
object for your class. Field
s for that class. Field
has the annotation Use
. If it does, get its fieldName
attribute and retrieve the corresponding element from the Map
. newInstance()
. Field
on that instance with the element you got from the Map
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.