why I can`t use method get(java.lang.reflect.Field#get) before changing field`s modifiers

前端 未结 2 720
孤街浪徒
孤街浪徒 2021-01-20 19:52

java code as follow.

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class Test {
    public static void main(Str         


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-20 20:12

    You are facing this issue because of the following line

    System.out.println(field.get(c));
    

    Since Field by default assumes the modifier as final, JDK will cache the field the moment you invoke any operations on it. Now, in your later part of the code you are modifying the access of the field through the following line

     modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
    

    But since you have not invalidated the Cache, you are getting the following exception.

    Hence, if you comment out the get statement, your access modifier logic will work without throwing any exceptions

    In a nutshell, you need to invoke your modifier logic before invoking any of the operations associated with field. The first time you invoke it, the metadata would be cached

提交回复
热议问题