Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...