Java reflection class private private variable Map and assign

Java reflection class private private variable Map and assign

import java.util.LinkedHashMap;
import java.util.Map;

public class MyObj {
    private String KEY = "NAME";

    //目标是通过反射在外部访问cache
    private Map<String, String> cache = new LinkedHashMap<>();

    public MyObj() {
        cache.put(KEY, "fly");
    }

    public void print() {
        System.out.println(cache.get(KEY));
    }
}

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        MyObj obj = new MyObj();
        System.out.println("反射前");
        obj.print();
        System.out.println("===");

        try {
            Field privateField = MyObj.class.getDeclaredField("cache");
            privateField.setAccessible(true);

            Map map = (Map) privateField.get(obj);

            System.out.println("-");
            Set<String> sets = map.keySet();
            Object[] keys = sets.toArray();
            for (Object k : keys) {
                System.out.println("遍历key-旧值:" + k + "->" + map.get(k.toString()));

                //对MyObj里面的cache设置新值。
                map.put(k, "phil");
            }
            System.out.println("--");


            System.out.println("反射后");
            obj.print();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

Java reflection changes Android properties_android reflection changes variable values_zhangphil's blog-CSDN blog Java reflection changes Android properties In some cases, some objects in the Android system do not provide external get methods for certain properties or classes. Or the set method, but the project needs to modify and adjust these. You need to use Java's reflection mechanism to modify the properties of Android. To give a simple example, change the height value of the Android ListView dividing line through the Java reflection mechanism. Android's ListView itself has a dividing line, and provides a _android reflection modification variable value that publicly sets the height of the dividing line https://blog.csdn.net/zhangphil/article/details/80138465

Java reflection class Class, reflection method Method and reflection variable Field_zhangphil's blog-CSDN blog Java reflection class Class, reflection method Method and reflection variable Fieldimport com.orhanobut.logger.Logger;import java.lang.reflect.Field;import java.lang .reflect.Method;import java.util.ArrayList;public class JavaActivity extends A... https://blog.csdn.net/zhangphil/article/details/80185335

kotlin class member variable field get/set_zhangphil's blog - CSDN blog kotlin class member variable field field get/set. https://blog.csdn.net/zhangphil/article/details/129233934

Guess you like

Origin blog.csdn.net/zhangphil/article/details/131935002