Set field value with reflection

前端 未结 5 749
天涯浪人
天涯浪人 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:54

    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();
    
                declaredField.setAccessible(true);
    
                ConcurrentHashMap concHashMap = new ConcurrentHashMap();
                concHashMap.put("key1", "value1");
                declaredField.set(this, concHashMap);
                Object value = ttp.get("key1");
    
                System.out.println(value);
    
                declaredField.setAccessible(accessible);
    
            } catch (NoSuchFieldException 
                    | SecurityException
                    | IllegalArgumentException 
                    | IllegalAccessException e) {
                e.printStackTrace();
            }
    
        }
    
        public static void main(String... args) {
            Test test = new Test();
            test.test(); 
        }
    }
    

    It prints :

    value1
    

提交回复
热议问题