如何从另一个类与java获取命令行参数 [英] how to get the command line arguments from another class with java

查看:114
本文介绍了如何从另一个类与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.....

我的问题是,有可能得到的args被传递到主方法从这些其他类不是主类的一部分,但在同一个包...

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

参数 abc ,输出:

Arg count is [3]
Arg[0] is [a]
Arg[1] is [b]
Arg[2] is [c]

这篇关于如何从另一个类与java获取命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆