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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With