0

Is there a way to modify the field of POJO with new property(like using MixIns or @JSONProperty) and get the modified POJO back ? (A way to add/modify field of a POJO dynamically ?)

Like I have a class

 class PojoA<T>{

 private T data;//field to be modified as NewData

 }

So, I tried with MixIns like

    public interface PojoMixIn<T> {
    @JsonProperty("NewData")
     T getData();
     }

Now to get the modified field, I use ObjectMapper

        mapper.addMixInAnnotations(PojoA.class,PojoMixIn.class);
        mapper.writerWithDefaultPrettyPrinter().writeValueAsString(pojoA);

The actual result is a String, but can I be able to get the modified POJO?

ewan.chalmers
  • 16,145
  • 43
  • 60
Jayanth
  • 329
  • 4
  • 15
  • I think this could be done using [reflection](http://docs.oracle.com/javase/tutorial/reflect/index.html), not sure if fasterxml will appreciate... – NiziL Aug 18 '14 at 13:13
  • Reflection, are you sure? isn't that costlier? – Jayanth Aug 18 '14 at 13:14
  • You want to change value of field, or change name of field? First one - reflection, second one - not possible (i think) – Antoniossss Aug 18 '14 at 13:21
  • Well, when I hear about modifying fields dynamically, I think about reflection.. But it's definitely not a cheaper solution, that's why I just comment your question ^^ – NiziL Aug 18 '14 at 13:21
  • @Antoniossss I am really in need of the second one, any ideas? – Jayanth Aug 18 '14 at 13:24
  • You would have to modify bytecode on fly - javaassist – Antoniossss Aug 18 '14 at 13:25
  • @Antoniossss Is the solution same for adding a new field in POJO dynamically? – Jayanth Aug 18 '14 at 13:28
  • You bet. There is no straightforward mechanism to do that. When you compile class the field definitions became constant. So if you would like to change this, you would need to change bytecode. When you do such tricks with JSon you are using some kind of preprocessor - all in all something has to process your annotations. Still, modifications are done with POJOS - eg. lets modify key name in map - simple. But here, you want to change definition of class on runtime, so the javaassist would be the way to do it – Antoniossss Aug 18 '14 at 13:35
  • @Antoniossss I agree! but my question is using Annotations fields can be changed, then can we change the value passed in the annotation later once it has been declared? – Jayanth Aug 18 '14 at 13:43

0 Answers0