user2749903 user2749903 - 4 years ago 113
Java Question

Java, set field value with reflection

Im 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.set(null, new ConcurrentHashMap<>());

Answer Source

Hope this is something what you are trying to do :

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class Test {

    private Map ttp = new HashMap(); 

    public  void test() {
        Field declaredField =  null;
        try {

            declaredField = Test.class.getDeclaredField("ttp");
            boolean accessible = declaredField.isAccessible();


            ConcurrentHashMap<Object, Object> concHashMap = new ConcurrentHashMap<Object, Object>();
            concHashMap.put("key1", "value1");
            declaredField.set(this, concHashMap);
            Object value = ttp.get("key1");



        } catch (NoSuchFieldException 
                | SecurityException
                | IllegalArgumentException 
                | IllegalAccessException e) {


    public static void main(String... args) {
        Test test = new Test();

It prints :

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download