reload a class so its static members are re-initialized

2.2k views Asked by At

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

1

There are 1 answers

6
ᴇʟᴇvᴀтᴇ On

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 with FIELD_1(), FIELD_2(). Then write some code to to replace the constants with static methods:

public static String FIELD_1() { return Env.getProperties("one"); }
public static String FIELD_2() { return Env.getProperties("two"); }
//etc.

It's a bit ugly, but it will get you where you want to be without resorting to real hacks.