Setting Global Variables in Java -


here's problem: have number of classes need access specific value (such email address) , instead of declaring again , again in each class i'd declare once , access using sort of global variable.

now before naysayers start screaming (or down-voting post) aware declare class this:

public class globalvar{          public globalvar() throws exception     {      }     public static string email = "myemail@gmail.com";   } 

and access email anywhere using globalvar.email

my problem value of email cannot set static because comes text file (from key/property using java properties class) , don't see anyway load value txt file if set variable static.

i storing dynamically generated email in file , retrieving next time start application. of course can attempt retrieve each time need use variable not elegant.

update:

a potential solution has been proposed follows:

public static string email = null; static {     email = "awesome@email.com"; // change initialization process } 

i thought solution work problem value generated dynamically @ startup if previous value not exist in txt file. basically, if 1st time running application new value generated. otherwise value retrieved txt file (which generated @ previous run of program).

if implement solution value of email equal null (across entire program) if first time run program.

i need way initialize static variable using conditional statement don't know if possible.

thanks

to initialize static variable can use static (see static initialization blocks):

public static string email = null; static {     email = "awesome@email.com"; // change initialization process } 

an alternative use static function:

class mail {     public static string email = initializemailvariable();      private static string initializemailvariable() {         // initialization code goes here     } } 

Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -