首页 > 解决方案 > 从 bash 脚本调用 java 进程时保持 java 对象状态

问题描述

    public class Go {
            private static SomeObject fld;
            public static void main(String[] args) {
                   //depending on the args I do call different methods(among 
                   //them one arg will do the job of initialization of fld variable)
            }
    }

我从 bash 脚本中调用了上面的 java 函数。

while true
do
    read commands
    java -cp some-jar.jar Go <commands>
then

假设 command1对Go类中的fld进行了初始化,而 command2 对初始化的字段进行了一些处理。

当我为不同的命令调用不同的 java 进程时,对象fld状态不会为下一个命令持久化。

如何修改代码,以便在不使用某些数据库或反序列化和序列化的情况下为下一个命令保留fld信息?

标签: javabash

解决方案


您可以将结果存储在 bash 变量中:

去.java

class Go {
    private static String fld;

    public static void main(String[] args) {
        fld = args[0];
        fld += fld.length();
        System.out.println(fld);
    }
}

运行.sh

VALUE=test

while true
do
    VALUE=`java  Go $VALUE`
    echo $VALUE
done

输出

test4
test45
test456
test4567
test45678

或者将结果存储到文件中,在 bash 中读取并作为参数传递给 Go.java 。

这是文件存储示例:

文件示例 Go.java

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

class Go {
    private static String fld;

    public static void main(String[] args) throws IOException {
        fld = args[0];
        fld += fld.length();
        FileWriter fileWriter = new FileWriter("store.txt");
        PrintWriter printWriter = new PrintWriter(fileWriter);
        printWriter.print(fld);
        printWriter.close();
    }
}

文件示例 run.sh

VALUE=store
while true
do

    java  Go $VALUE
    VALUE=`cat ./store.txt`
    echo $VALUE
done

文件示例输出

store5
store56
store567
store5678

推荐阅读