java - 从 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信息?
解决方案
您可以将结果存储在 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
推荐阅读
- python - plotly networkx图中的滑块
- r - 基于列名部分匹配的另一个数据帧索引到一个数据帧
- npm - 如何直接从终端检查包/插件的更新?
- ios - 在 Swift 中为 searchBar 结果过滤和排序数组
- php - PHP数组没有遍历块的第一部分
- javascript - 为什么我的 HTML 元素 javascript 变量与我在 DOM 中看到的不匹配?
- python - 我想将列表添加到从 SELECT db.execute 查询创建的字典中,然后遍历更新的字典
- java - 在静态变量/方法上调用实例方法的替代方法?
- c++ - 为什么布尔 switch 语句有编译器警告?
- python-3.x - 为什么我会收到此错误--> ( IndentationError: unexpected unindent )?