2
votes

I want to to add an extra filed(e.g a UUID) to the Object i.e going to be serialized or already serialized at runtime using javassist or reflection.

Is it possible?

2

2 Answers

0
votes

Short answer

You cannot do it as you want but maybe there are other ways

Long answer

So let's start from some definitions:

Javassist: is a class library for editing bytecode in Java. It enables Java programs to define a new class at runtime and to modify a given class file when the JVM loads it.

Reflection: is a feature in the Java programming language. It allows an executing Java program to examine or introspect upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.

So as I highlighted with Javassist you can easily add a field to a class but only at load time (meaning when the JVM is loading the classes into its memory).

With reflection instead is possible to lookup at the properties of a class and even modify them, however there is no way off adding new properties.

My proposal

I don't now if this is is feasible for your usecase but the solution may to use them both:

  1. Using Javassist add the UUID filed to the classes that may need it at load time
  2. Before serializing the object, you can use Reflection to actually set this UUID field to the desired value and then serialize it
0
votes

Actually, it is possible without reflection without needing to have any window to the Class whose object you want to add the custom property to - It can be done by first converting your object to an Attribute Map like this,

Here is a method I have written for this,

     /**
     * To convert the current Object to a AttributeMap. This allows for using this map
     * to add to it in a subclass additional attributes for Serialization. It would be
     * required in a scenario when you want to alter the simple Jackson Serialization
     * methodology(where you just annotate the fields to be included in Serialization
     * and that's it.). A non-simple scenario would involve adding custom fields decided
     * at runtime 
     * @return The AttributeMap of this object.
     */
    protected Map<String, Object> toAttributeMap(Object object){
        return objectMapper.convertValue(object, new TypeReference<Map<String, Object>>() {
        });
    }

Now, you can add to this Attribute Map for the object and then put()-ing your fields and convert it to maybe a JSON string.


Notes about the answer:

  • It uses Jackson's Object Mapper API.
  • It doesn't use JavaAssist.