如何使用java从另一个类获取命令行参数

2022-01-23 00:00:00 class command main command-line java

所以假设我有一个 java 包....

so suppose I have a java package....

它有带有main方法的主类

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

推荐答案

不,不便携,基于JVM实现可能会有一些诡计但我从未见过,依赖它会是一个非常糟糕的主意即使它存在.

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.

如果您想在其他地方使用这些值,main 函数需要以某种方式使它们可用.

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

一种简单的方法(不一定是最好的方法)是简单地将字符串作为第一件事存储在 main 中,并提供一种获取方法他们:

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] + "]");
        }
    }
}

并且,当使用参数 a b c 运行时,会输出:

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]

相关文章