lundi 13 septembre 2021

Java reflection: add final modifier to a class field

I'm looking for a way to make an object immutable dynamically by setting all properties of a POJO to be final. One way I thought of is to use Java Reflection to set the modifier to final.

Consider the following POJO:

public class Task {

   private String id;
   private String code;

   // getters and setters placed here

}

Using the above POJO example, I'd like to make id and code have a final modifier. By researching some examples on the internet, these examples refer to using bitwise operators to unset the final modifier.

e.g. the common line that does that is:

modField.setInt(idField, idField.getModifiers() & ~Modifier.FINAL);

However, is there an example of setting the FINAL modifier to a field? thanks.





Aucun commentaire:

Enregistrer un commentaire