JDK高版本反射修改 private static fianl 修饰的对象

在 JDK 高版本中,Java 语言规范已经更新,因可能会破坏 Java 语言的安全性和稳定性,不再允许通过反射改变 final 字段的值,需要自己做一下处理。

 

创建工具类

import java.lang.reflect.Field;
import sun.misc.Unsafe;

public class FieldUtil{

    private static Unsafe unsafe;

    static{
        try{
            final Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
            unsafeField.setAccessible(true);
            unsafe = (Unsafe) unsafeField.get(null);
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

    public static void setFinalStatic(Field field, Object value) {
        try {
            Object fieldBase = unsafe.staticFieldBase(field);
            long fieldOffset = unsafe.staticFieldOffset(field);
            unsafe.putObject(fieldBase, fieldOffset, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

创建测试类

public class My{ 
    private static final a = new BigInteger("123456");
}

 

反射修改private static final 修饰的字段值

 

Field e = My.class.getDeclaredField("a");
e.setAccessible(true);
System.out.println("e update before: " + e.get("e"));
FieldUtil.setFinalStatic(e, new BigInteger("1"));
System.out.println("e update after: " + e.get("e"));

输出结果:
e update before: 123456
e update after: 1

 

 
posted @ 2023-05-31 17:39  sevennight  阅读(496)  评论(0编辑  收藏  举报