1

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

One Two Three
  • 22,327
  • 24
  • 73
  • 114

1 Answers1

1

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.

ᴇʟᴇvᴀтᴇ
  • 12,285
  • 4
  • 43
  • 66
  • It's not a problem of different callers get different values (because that's exactly what I'd want). – One Two Three Dec 16 '13 at 19:32
  • 1
    @aetheria OP may just be that next guy or girl since the previous coder decided to do it this way... – MxLDevs Dec 16 '13 at 19:55
  • @OneTwoThree to me that sounds like questionable design. I don't know what these "various reasons" are but if you have the option to improve the design without breaking a dozen applications I would consider improving the design. Bad design usually always becomes a problem later on, when it's really hard to change. – MxLDevs Dec 16 '13 at 19:58
  • Well, OK I admit these "various reasons" include "this file is 3,000+ lines in length, with (as many fields). And I am not in the mood of re-writing all these. (And that wasn't counting the callers)" – One Two Three Dec 16 '13 at 20:02
  • I feel for you! Could you write some code that performs a refactoring on the Java files? i.e. reads in Java file, alters the way the fields are accessed and writes out a new version? At least then it's not a manual effort. – ᴇʟᴇvᴀтᴇ Dec 16 '13 at 20:08
  • I've added a refactoring suggestion. – ᴇʟᴇvᴀтᴇ Dec 16 '13 at 20:18