I'm working with one project which is not opensource and I need to modify one or more its classes.
In one class is following collection:
private Map<Integer, TTP> ttp = new HashMap<>();
All what I need to do is use reflection and use concurrenthashmap here. I've tried following code but it doesnt work.
Field f = ..getClass().getDeclaredField("ttp");
f.setAccessible(true);
f.set(null, new ConcurrentHashMap<>());
It's worth reading Oracle Java Tutorial - Getting and Setting Field Values
Field#set(Object object, Object value) sets the field represented by this
Field
object on the specified object argument to the specified new value.It should be like this
You can't set any value in
null
Object If tried then it will result inNullPointerException
Note: Setting a field's value via reflection has a certain amount of performance overhead because various operations must occur such as validating access permissions. From the runtime's point of view, the effects are the same, and the operation is as atomic as if the value was changed in the class code directly.
You can try this:
You can try this:
}
The method below sets a field on your object even if the field is in a superclass
Hope this is something what you are trying to do :
It prints :