Supposed I have a class like the following
public class Foo
{
public static final String FIELD_1 = Env.getProperties("one");
public static final String FIELD_2 = Env.getProperties("one");
//....
public static final String FIELD_N = Env.getProperties("n");
}
Obviously, all the FIELD_*
get populated when we first reference Foo
.
Suppose my Env.getProperties(String)
is not purely functional (ie., it could return different values. How? Not important here)
How do I force the class Foo
to be "reloaded", so that all the class-init code is re-excecuted (just so I could have different values for the static fields)?
(For various reason, I can't make these fields non-static or non-final. So please don't suggest solutions like make Foo an interface, with various getter-methods to be overriden)
Thanks
Don't do it!
You may be able to do it with a custom classloader or JRebel but it will be a mega-bodge. Different classes may have read different values from these fields and be out of sync with each other etc.
Constants are supposed to be constant. Follow the principle of least astonishment and refactor to a better design.
Minimal refactoring suggestion
If the fields are reasonably well-named -
FIELD_1
,FIELD_2
etc. - you may be able to search and replace references to them in all the Java files withFIELD_1()
,FIELD_2()
. Then write some code to to replace the constants with static methods:It's a bit ugly, but it will get you where you want to be without resorting to real hacks.