Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the command line arguments from another class with java

so suppose I have a java package....

it's got the main class with the main method

and then it's got a whole bunch of other classes.....

my question is, is it possible to get the args that was passed into the main method from these other classes that are not part of the main class but in the same package...

like image 357
kamikaze_pilot Avatar asked Feb 21 '11 01:02

kamikaze_pilot


1 Answers

No, not portably, there may be some trickery based on the JVM implementation but I've never seen it, and it would be a very bad idea to rely on it even if it existed.

If you want those values elsewhere, the main function needs to make them available somehow.


An easy way to do this (not necessarily the best way) is to simply store away the strings as the first thing in main and provide a means for getting at them:

Scratch2.java:

public class Scratch2 {
    // Arguments and accessor for them.

    private static String[] savedArgs;
    public static String[] getArgs() {
        return savedArgs;
    }

    public static void main(String[] args) {
        // Save them away for later.

        savedArgs = args;

        // Test that other classes can get them.

        CmdLineArgs cla = new CmdLineArgs();
        cla.printArgs();
    }
}

CmdLineArgs.java:

public class CmdLineArgs {
    public void printArgs() {
        String[] args = Scratch2.getArgs();
        System.out.println ("Arg count is [" + args.length + "]");
        for (int i = 0; i < args.length; i++) {
            System.out.println ("Arg[" + i + "] is [" + args[i] + "]");
        }
    }
}

And, when run with the arguments a b c, this outputs:

Arg count is [3]
Arg[0] is [a]
Arg[1] is [b]
Arg[2] is [c]
like image 193
paxdiablo Avatar answered Oct 09 '22 11:10

paxdiablo