是的,这种方式很好,但你不能在构造函数方法中运行python脚本,如果是这样,它将在你的代码中死亡递归。请参阅以下代码。你运行PythonScriptTest类,它将首先运行python脚本,然后python脚本将调用PythonScriptTest.SpawnPlayer()方法。
java代码:
package com.xxx.jython;
import org.python.core.PyFunction;
import org.python.util.PythonInterpreter;
public class PythonScriptTest {
public static void main(String[] args) {
PythonScriptTest f = new PythonScriptTest();
f.executePythonScript();
}
public PythonScriptTest(){
}
public void executePythonScript() {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("/home/XXX/XXX/util.py");
PyFunction pyFuntion = (PyFunction) interpreter.get("InGameCommand", PyFunction.class);
pyFuntion.__call__();
}
public void SpawnPlayer() {
System.out.println("Run SpawnPlayer method ##################");
}
}Python脚本,名为util.py:
import sys.path as path
# the following path is eclipse output class dir
# does not contain java class package path.
path.append("/home/XXX/XXX/Test/bin")
from com.xxx.jython import PythonScriptTest
def add(a, b):
return a + b
def InGameCommand():
myJava = PythonScriptTest()
myJava.SpawnPlayer()