Is there a way to modify a POJO field and return the POJO
Asked Answered
B

0

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?

Baber answered 18/8, 2014 at 13:7 Comment(9)
I think this could be done using reflection, not sure if fasterxml will appreciate...Zeiler
Reflection, are you sure? isn't that costlier?Baber
You want to change value of field, or change name of field? First one - reflection, second one - not possible (i think)Stgermain
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 ^^Zeiler
@Stgermain I am really in need of the second one, any ideas?Baber
You would have to modify bytecode on fly - javaassistStgermain
@Stgermain Is the solution same for adding a new field in POJO dynamically?Baber
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 itStgermain
@Stgermain 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?Baber

© 2022 - 2024 — McMap. All rights reserved.