简体   繁体   中英

How can i use annotation to load values for a field in java

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.

  1. Create your Map .
  2. Get the Class object for your class.
  3. Get the declared Field s for that class.
  4. Check if each Field has the annotation Use . If it does, get its fieldName attribute and retrieve the corresponding element from the Map .
  5. Create an instance of your class with some version of newInstance() .
  6. Set each found Field on that instance with the element you got from the Map .
  7. Handle type conversion, invalid types or fields that don't have a corresponding element.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM