In my Java web server project, my Main.main
method takes an argument specifying the directory where it will look for certain files, that I use later on. My issue is that I don't actually do anything with that argument in my higher-level classes, but the information is needed by some of my lower-level ones.
Naturally, the class that parses and stores my command line arguments is one of the first ones that is used, i.e. one of my highest level classes, so I'm struggling to find a way to make the command line argument accessible to my low-level classes.
It seems like my only two options are to either pass it all the way down, through classes that never touch the argument other than to pass it to the next level, or to give it a global scope. Neither of these seem like great options from a design perspective, so I'm wondering if there's an alternative that I'm missing, or if I just have to pick the lesser of two evils-- or totally revamp the way my classes are structured.
Yes there are many options to do that:
Use system property instead of main
method parameter and
a. call your main as >java -Dmy.path=path_to_directory
Main
b. use environment variable
>set my.path=path_to_directory
>java Main
c. set it in the main
method:
public void main(String[] args) {
System.getProperties().put("my.path",args[dirPathIndex]);
In all cases you can get a value anywhere in the code just as:
String dirPath=System.getProperty("my.path");
Create a small local static "kind of cache" in Main class
public class Main{
public static String dirPath;
public void main(String[] args) {
dirPath= args[dirPathIndex];
Then also, anywhere in the code you can get it as:
`String dPath=Main.dirPath;`
Of course there are more options around "local cache" approach, but main idea still the same. Keep a value somewhere, you can get it at any place in the code.