Python Jpype在JAR文件中看不到Java类

问题描述

我正在尝试解决应该是一个简单的问题,但是缺少一些东西。我有一个非常简单的java类

package blah.blah;

public class Tester {
    public String testMethod1() { return "GotHere"; }
    public String testMethod2() { return "GotHeretoo"; }
} // Tester

我正在尝试将其加载到JPype中:

import jpype
import jpype.imports
from jpype.types import *

path_to_jvm = "C:\\Java\\OracleJDK-8_241_x64\\jre\\bin\\server\\jvm.dll"
jpype.startJVM(path_to_jvm,classpath=["C:\\Users\\Administrator\\eclipse-workspace\\JpypeTest\\src;"])

from java.lang import System
print(System.getProperty("java.class.path"))

from java.io import ObjectInputStream
from blah.blah import Tester

tester = Tester()
print(tester.testMethod1())
print(tester.testMethod2())

jpype.shutdownJVM()

当我使用上面的代码直接加载类时,一切工作正常。当我尝试通过JAR加载Class文件时,它停止工作。

jpype.startJVM(path_to_jvm,classpath=["C:\\Users\\Administrator\\JpypeTest.jar;"])

我得到的错误是:

Traceback (most recent call last):
  File ".\jpype_test.py",line 16,in <module>
    from blah.blah import Tester
ModuleNotFoundError: No module named 'blah'
PS C:\Users\Administrator> python .\jpype_test.py
C:\Users\Administrator\JpypeTest.jar;
Traceback (most recent call last):
  File ".\jpype_test.py",in <module>
    from blah.blah import Tester
ModuleNotFoundError: No module named 'blah'

从Eclipse 2020/09开始,我使用JAR导出以多种方式构建了JAR文件,并在命令行中使用了以下方式:

C:\Users\Administrator\eclipse-workspace\JpypeTest\src>"C:\Java\OracleJDK-8_241_x64\bin"\jar cf C:\Users\Administrator\JpypeTest.jar blah\blah\*.class

我已经确认JVM和python解释器都是64位的。我还尽力确保Eclipse,命令行和Python之间的JVM完全相同。

从我的看到,无论我如何构建,JAR都看起来不错。它包含blah \ blah目录及其下的Tester.class文件。清单是JAR中唯一的其他文件

我还尝试过使用类文件在不同目录级别(即,一个级别的blah目录而没有级别的blah目录)创建JAR文件

以下是python软件的版本:

Python 3.8.5 (default,Sep  3 2020,21:29:08) [MSC v.1916 64 bit (AMD64)] :: Anaconda,Inc. on win32
Package      Version
------------ -------------------
certifi      2020.6.20
JPype1       1.0.2
pip          20.2.3
setuptools   50.3.0.post20201006
wheel        0.35.1
wincertstore 0.2

我显然可以使基础管道正常工作,因为它可以看到类文件。关于JAR为何失败的任何想法?

感谢您的考虑。

解决方法

检查您是否没有python查找模块的目录“ blah”。根据{{​​3}},这将隐藏您的Java类:

在处理导入Java模块时的一个重要警告。在调用Java导入程序之前,Python始终将本地目录作为模块导入。因此,任何名为java,com或org的目录都将隐藏相应的Java程序包。建议不要将目录命名为Java或顶级域。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...