Here's my problem: I have a number of classes that need access to a specific value (such as an email address) and instead of declaring it again and again in each class I'd like to declare it once and access it using some sort of global variable.
Now before you naysayers start screaming (or down-voting this post) I am aware you could declare a class like this:
public class GlobalVar{
public GlobalVar() throws Exception
{
}
public static String email = "[email protected]";
}
And access email anywhere by using GlobalVar.email
My problem is the value of email cannot be set as static because it comes from a text file (from key/property using Java properties class) and I don't see anyway to load the value from txt file if I set the variable to static.
I am basically storing a dynamically generated email in a file and retrieving it the next time I start the application. Of course I can attempt to retrieve it each time I need to use the variable but this is not elegant.
Update:
A potential solution has been proposed as follows:
public static String email = null;
static {
email = "[email protected]"; // change to your initialization process
}
I thought this solution would work however the problem is that the value is generated dynamically at startup if a previous value does not already exist in the txt file. Basically, if it is the 1st time you are running the application a new value is generated. Otherwise the value is retrieved from a txt file (which was generated at a previous run of the program).
If I implement this solution the value of email will be equal to null (across the entire program) if this is the first time you run the program.
I basically need a way to initialize a static variable using a conditional statement but I don't know if this is possible.
Thanks
staticinitialize to load it. Have a look at Initializing Fields for more details.Unhandled exception type IOException(unless I initialize variable usingstatic { }as some suggested.GlobalVar.setEmailor something? so you can change the email whenever you wantPropertiesobject whenver you need it. the properties API is designed for this sort of thing