Java 通过Jython加载Python类

Java 通过Jython加载Python类,java,jython,Java,Jython,我试图通过在Java应用程序中嵌入Jython来加载Python类 到目前为止,我掌握的代码是 String pythonRoot = Main.class.getResource("/python").getPath(); PySystemState state = new PySystemState(); PyObject importer = state.getBuiltins().__getitem__(Py.newString("__import__"

我试图通过在Java应用程序中嵌入Jython来加载Python类

到目前为止,我掌握的代码是

String pythonRoot = Main.class.getResource("/python").getPath(); PySystemState state = new PySystemState(); PyObject importer = state.getBuiltins().__getitem__(Py.newString("__import__")); PyObject sysModule = importer.__call__(Py.newString("sys")); final PyString pythonPath = Py.newString(pythonRoot); PyList path = (PyList) sysModule.__getattr__("path"); path.add(pythonPath); PyModule module = (PyModule) importer.__call__(Py.newString("building.blah.again.blah2.Test")); PyObject klass = module.__getattr__(Py.newString("Address")); AddressInterface ai = (AddressInterface) klass.__call__().__tojava__(AddressInterface.class); 字符串pythonRoot=Main.class.getResource(“/python”).getPath(); PySystemState=新PySystemState(); PyObject importer=state.getBuiltins()。\uuuuGetItem\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu; PyObject sysModule=importer.\uuuu调用(Py.newString(“sys”); final PyString pythonPath=Py.newString(pythonRoot); PyList路径=(PyList)系统模块; add(pythonPath); PyModule模块=(PyModule)导入程序; PyObject klass=module; AddressInterface ai=(AddressInterface)klass.\uuuuu调用\uuuuu()。\uuuu到Java\uuuuu(AddressInterface.class); 可以在中找到我尝试访问的类

/python/building/blah/again/blah2/Test.py /python/building/blah/reach/blah2/Test.py 类的名称是

Address 住址 然而,这给了我一个例外

Exception in thread "main" ImportError: No module named blah2 Exception in thread "main" ImportError: No module named again 线程“main”导入中出现异常错误:没有名为blah2的模块 如果我把一些文件放在上面的目录中,就像这样

/python/building/blah/again/Test.py /python/building/blah/reach/Test.py 这给了我一个例外

Exception in thread "main" ImportError: No module named blah2 Exception in thread "main" ImportError: No module named again 线程“main”导入中出现异常错误:没有再次命名模块
就好像他主动拒绝识别包含文件的目录一样。这里会出现什么问题?我该如何解决这个问题?

如果您通过
path.add(pythonPath)将模块的路径添加到Python路径中,导入命令只需要模块的名称,而不需要完整路径,即
PyModule module=(PyModule)导入器
此外,您应该通过打印路径列表的内容来确认是否添加了正确的路径。还要注意,Test.py中的类声明必须扩展Address java接口,才能使
toJava
正常工作(我之所以提到这一点,是因为这也是常见的错误源)

也就是说,我觉得你使用Jython的方式有点麻烦。如果我是你,我会在python脚本中做这些事情(添加路径,进行导入),通过
org.python.util.PythonInterpreter
()运行它,并通过
eval
get
-方法检索类PyObject