-1

I am trying to upgrade my application Java version from v1.8 to v17. There are some unit tests which are using Reflection to set value of private, static, final fields. I tried using VarHandle but no luck.

@user207421 agree could have added more details. Whatever threads are marked as possible duplicate of not solving my problem. And there are mixed responses to the question. Some say can not done and period. More important is version of Java with respect to which they are suggesting the solution is not clear. We have a working code which sets static final field values using Reflection. We use it only for tests. Now we are upgrading Java from v1.8 to v17 any approach which uses Field.class.getDeclaredField("modifiers"); will not work. I tried using VarHandle in conjunction with setting --add-open to VM arg but it makes my runtime to crash. I will post my code sameple shortly .. any ideas would help.

Vinay
  • 7
  • 3
  • 2
    Possible duplicate of [Change private static final field using Java reflection](https://stackoverflow.com/questions/3301635/change-private-static-final-field-using-java-reflection) – pppery May 10 '22 at 20:44
  • 1
    @pppery this is not a duplicate. None of the suggestion from accepted answer are working on Java v17. Its worth to open up this discussion and feel it will help lot of developers. – Vinay May 12 '22 at 10:08
  • 3
    [You can't change `static final` fields in Java.](https://gist.github.com/DasBrain/ca16053f8e073c8a883bee66302c2fee) Period. If you have a need to do that, then the variable should not be `final`. If you really have to, an agent can drop the `final` modifier before the class is loaded. – Johannes Kuhn May 12 '22 at 16:40
  • As a general policy, the outdatedness of answers is irrelevant in determining whether a question is a duplicate. – pppery May 12 '22 at 23:18
  • 1
    How does the answers in the "duplicate" answer the question "Is it possible to set private static final field using Reflection in JDK 17?". – Johannes Kuhn May 13 '22 at 06:47
  • 1
    'No luck' is not a problem description, and neither is anything else here. – user207421 May 13 '22 at 07:41
  • 1
    @user3676248 Did you try out the code [I linked](https://gist.github.com/DasBrain/ca16053f8e073c8a883bee66302c2fee) on Java 8? Changing `static final` fields was never supported and may only sporadically work. – Johannes Kuhn May 18 '22 at 12:41

0 Answers0