dimanche 19 novembre 2017

How to make mutable fields of a Java Bean immutable at run time using reflection

I am getting some Java objects from a library which have mutable map objects as fields. I need a way to make those object fields read only at run time by wrapping the map objects in Collections.unmodifiableMap() method. I have tried the below approach using Java Reflection API, but I am stuck at getting the actual map instance from the field:

public static <T>T freeze(T obj){
    if(obj!=null){
        Field[] fields=obj.getClass().getDeclaredFields();
        for(Field field:fields){
            if(field.getType().equals(Map.class)){
                //How to wrap a Map instance from the field in Collections.unmodifiableMap() object
            }
        }
    }
    return obj;
}





Aucun commentaire:

Enregistrer un commentaire