TimeCollectTime
2021-07-29 09:20
采纳率: 80%
浏览 56
已结题

对String的value进行反射set报出一堆warning和IllegalArgumentException异常

public static void main(String[] args) throws Exception{
        String s="abc";
        Class<? extends String> cls = String.class;
        Field value = cls.getDeclaredField("value");
        value.setAccessible(true);
        value.set(s,"abcd".toCharArray());
        System.out.println(s.hashCode());
}


报错:
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by Demo (file:/D:/1.%e5%9e%83%e5%9c%be%e7%ab%99/JAVA/%e5%8f%8d%e5%b0%84/out/production/%e5%8f%8d%e5%b0%84/) to field java.lang.String.value
WARNING: Please consider reporting this to the maintainers of Demo
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
Exception in thread "main" java.lang.IllegalArgumentException: Can not set final [B field java.lang.String.value to [C
at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
at java.base/jdk.internal.reflect.UnsafeQualifiedObjectFieldAccessorImpl.set(UnsafeQualifiedObjectFieldAccessorImpl.java:83)
at java.base/java.lang.reflect.Field.set(Field.java:780)
at Demo.main(Demo.java:10)

  • 好问题 提建议
  • 收藏

3条回答 默认 最新

  • CSDN专家-微编程 2021-07-29 09:26
    已采纳

    img
    你将你的jdk改成1.8版本试试,不要超过1.8

    已采纳该答案
    评论
    解决 2 无用 1
    打赏 举报
  • CSDN专家-sinjack 2021-07-29 09:26

    img
    好像并没啥问题,我这边测试正常。
    检查一下看是否是环境导致的。

    评论
    解决 无用
    打赏 举报
  • Coding不良人 2021-07-29 09:35

    应该是string的value是用final修饰的,所以你改不了
    img
    StringBuffer和StringBuilder应该就能改了

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题