I currently define a class for constants like this
public final class DataContainer{
public static final String x1="a";
public static final String x2="b";
...
public static final String xn="z";
}
& use these simply by accessing like this : DataContainer.x1
But now I need to define two implementation of this constants file(DataContainer1 & DataContainer2) & choose during runtime which of the two implementation class of constants to use throughout the application, without changing everywhere from DataContainer1.x1 to DataContainer2.x1.
How can I implement such a design ?
You should probably move away from a
static finalimplementation of your constants.The main advantage of having static/final constants in the first place is that the compiler has access to these values already at compile time, and can thus perform various optimizations.
But since you need to be able to exchange the actual values of the constants at runtime, that advantage will be gone anyway. Strictly speaking, one could argue that the values are no longer constants in the strictest sense, since they are actually variable.
I would probably just go for a very simple and classic OO construction, where you have a map-like interface to the values and different implementations thereof.
(As a matter of fact, switching to a
java.util.Mapor tojava.util.Propertiesmay already do what you’re looking for.)Of course you may still want to define the values in the individual implementations of that interface as
static final.If you’re absolutely in love with static access, you could use a Factory pattern to retrieve the actual instance of the constants at runtime. That will also totally make you look like a certified Java guru amongst your coworkers 😉