Set field value with reflection

前端 未结 5 743
天涯浪人
天涯浪人 2020-12-01 10:00

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         


        
5条回答
  •  独厮守ぢ
    2020-12-01 10:38

    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

    f.set(objectOfTheClass, new ConcurrentHashMap<>());
    

    You can't set any value in null Object If tried then it will result in NullPointerException


    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.

提交回复
热议问题