Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify a Static Variable when accessed

Tags:

java

From what I know about java I don't think this is possible but I would like to pose this question to people with far more knowledge than I do.

If I have a static variable say,

public static String NAME = "james";

Is there any way, through reflection or otherwise, to create a listener for said variable such that if someone else calls:

ClassName.NAME

It can be modified before they get the result, so I can change the value of NAME so that it equals "simon" instead?

To be clear, this code base is not my own and I can not change the variable to instead use getters and setters. I know that would make this much simpler, but that isn't an option unfortunately.

like image 469
Andrew T. Avatar asked Mar 21 '26 18:03

Andrew T.


2 Answers

No, you can't. That's one of the reasons why you shouldn't use public variables. Always use private or protected variables and access them through a getter-method like static public String getName(). That way you can put any logic into the getter you want.

like image 68
Philipp Avatar answered Mar 23 '26 09:03

Philipp


There is a saying in computer science that you can achieve anything by "Another level of indirection", thus use an access method:

public class Foo {

    private static String name;

    public static String getName () {
        String result = name;
        //do a lot of other things.
        return result;
    }


}

Otherwise, I think it is not possible. You could rewrite the byte code: such that every call to the item is replaced by first doing some other things. But this is very complex.

If it's not your own, you can't do it, unless with an enormous effort (rewriting bytecode).

like image 30
Willem Van Onsem Avatar answered Mar 23 '26 07:03

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!