I'm trying to overwrite the value of a non-static final field through Reflection in Java 17.
As far as I know, you can no longer do the following trick starting with Java 12 and above:
import java.lang.reflect.*;
class Foo {
private final String bar;
public Foo(String bar) {
this.bar = bar;
}
public String getBar() {
return this.bar;
}
}
public class Example {
public static void main(String[] args) {
Foo foo = new Foo("foobar");
System.out.println(foo.getBar());
try {
Field field = foo.getClass().getDeclaredField("bar");
field.setAccessible(true);
Field modifiers = field.getClass().getDeclaredField("modifiers");
modifiers.setAccessible(true);
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(foo.getBar());
}
}
When I run this in Java 17, the following exception is thrown:
foobar java.lang.NoSuchFieldException: modifiers at java.base/java.lang.Class.getDeclaredField(Class.java:2610) at Example.main(Example.java:24) foobar
And the value of 'bar' remains unchanged.
Is there an equivalent method of overwriting a final field for the newer versions of Java? A quick search in Google didn't yield anything different from the above solution. The only thing I learned was that it is impossible to overwrite a static final field, while it's still possible to overwrite a non-static final field through Reflection, but I couldn't find out how.