对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)
发表回复