简体   繁体   English

在批处理文件中调用 java class 并将“main”方法的返回值存储在批处理变量中

[英]Call java class in batch file and store the return value of the "main" method in batch variable

Is it possible to run a java class in a batch file with a main method inside, changing the return type of the method from "void" to another type, and get the return value in batch file?是否可以在批处理文件中运行 java class 并在其中包含 main 方法,将方法的返回类型从“void”更改为另一种类型,并在批处理文件中获取返回值?

I mean something similar to the following:我的意思是类似于以下内容:

Java class: Java class:

public class Main{

    public static String main(String[] args) {
        public String returnValue;
        
        // code to execute...
        
        return returnValue;
    }
}

Batch file:批处理文件:

...
set RETURNVALUE = ""
//call "java com.test.Main" and store return value in RETURNVALUE variable
...

I need to make some checks in the java class, and then execute the subsequent instructions in batch file according to the result given by the java class.我需要在java class中做一些检查,然后根据java class给出的结果执行批处理文件中的后续指令。

Any help will be appreciated任何帮助将不胜感激

You can end the main method with System.exit() instead of return:您可以使用 System.exit() 而不是 return 结束 main 方法:

public class Main{
    public static void main(String[] args) {
        int returnValue;

        // code to execute...
        returnValue = 123;
        
        System.exit(returnValue);
    }
}

Then in the script:然后在脚本中:

#!/bin/bash

java ./Main.java
RETURNVALUE=$?

echo "The return value was $RETURNVALUE"

which gives you:这给你:

$ ./script.sh  
The return value was 123

The exit code can't be a string, only a number from 0 to 255. If you want to return a string instead, consider printing to stdout instead and saving that to a variable.退出代码不能是字符串,只能是 0 到 255 之间的数字。如果要返回字符串,请考虑改为打印到标准输出并将其保存到变量中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM