我创建了一个PythonInterpreter对象,想要调用java函数但不断收到错误:
Exception in thread "main" Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: name 'jytest2' is not defined
Java Result: 1
如何从实时运行的系统调用java函数?
public static void main(String args[])
{
ModRet modRet = new ModRet();
jytest();
}
public void jytest()
{
PythonInterpreter interp = new PythonInterpreter();
interp.exec("print \'Hello; jython has successfully been embedded!\'");
interp.exec("print " + FPS);
interp.exec("jytest2()");
}
public void jytest2()
{
System.out.println("HIHIHI");
}
答案 0 :(得分:1)
我通常发现我需要使用Object Factory模式并通过接口调用内容,如Jython Book - Chapter 10
中所述我仍然不太清楚你想要完成什么,所以我没有任何代码给你;但我相信你会发现这本书很有帮助。
答案 1 :(得分:1)
默认情况下,当前的类路径包含在jython路径中。要访问路径中的任何方法,您应该进行导入。
package com.mycompany.jythontest;
import org.python.util.PythonInterpreter;
public class App
{
public static void sayHello(String hello) {
System.out.println(hello);
}
public static void main( String[] args )
{
PythonInterpreter py = new PythonInterpreter();
py.exec("from com.mycompany.jythontest import App");
py.exec("App.sayHello('hello')");
}
}
如果要在jython中访问java实例,可以使用py.set(string, object)
使其在上下文中可访问。 (就像javax.scripting一样)
App app = new App();
py.set("appinstance", app);
py.exec("appinstance.sayHi('hello world')");