Note that there are some explanatory texts on larger screens.

plurals
  1. POIs there any way to modify the value of a `private static final` field in Java from outside the class?
    primarykey
    data
    text
    <p>I know this is normally rather stupid, but don't shoot me before reading the question. I promise I have a good reason for needing to do this :)</p> <p>It's possible to modify regular private fields in java using reflection, however Java throws a security exception when trying to do the same for <code>final</code> fields.</p> <p>I'd assume this is strictly enforced, but figured I'd ask anyway just in case someone had figured out a hack to do this. </p> <p>Let's just say I have an external library with a class "<code>SomeClass</code>"</p> <pre><code>public class SomeClass { private static final SomeClass INSTANCE = new SomeClass() public static SomeClass getInstance(){ return INSTANCE; } public Object doSomething(){ // Do some stuff here } } </code></pre> <p>I essentially want to Monkey-Patch SomeClass so that I can execute my own version of <code>doSomething()</code>. Since there isn't (to my knowledge) any way to really do that in java, my only solution here is to alter the value of <code>INSTANCE</code> so it returns my version of the class with the modified method.</p> <p>Essentially I just want to wrap the call with a security check and then call the original method. </p> <p>The external library always uses <code>getInstance()</code> to get an instance of this class (i.e. it's a singleton).</p> <p>EDIT: Just to clarify, <code>getInstance()</code> is called by the external library, not my code, so just subclassing won't solve the issue. </p> <p>If I can't do that the only other solution I can think of is to copy-paste entire class and modify the method. This isn't ideal as I'll have to keep my fork up to date with changes to the library. If someone has something a little more maintainable I'm open to suggestions. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload