我正在尝试使用Py4J从 Python访问Java DAO方法,但遇到了一个奇怪的问题。我有以下文件。我可以正确编译,它似乎可以从 Python 使用Py4J工作:MyApplication.java
import py4j.GatewayServer;
import company.common.dao.DAOFactory;
import company.sys.dao.ABCartDAO;
public class MyApplication {
public String foo (int n) {
ShoppingCart bar = DAOFactory.getDAO(ABCartDAO.class);
String identifier bar.findit(n)
return identifier;
}
public static void main(String[] args) {
MyApplication app = new MyApplication();
GatewayServer server = new GatewayServer(app);
server.start();
}
}
我可以用java MyApplication
. 但是,当我在 Python 中运行以下命令时:
from py4j.java_gateway import JavaGateway
gateway = JavaGateway() # connect to the JVM
# Testing that it works
random = gateway.jvm.java.util.Random() # create a java.util.Random instance
number1 = random.nextInt(10) # call the Random.nextInt method
number2 = random.nextInt(10)
print(number1,number2)
my_application = gateway.entry_point
my_application.foo(4)
获取随机数是有效的(证明 Py4J 正在完成它的工作),但其中的操作调用失败:
---------------------------------------------------------------------------
Py4JJavaError Traceback (most recent call last)
<ipython-input-14-d2345f6205bf> in <module>()
----> 1 my_application.foo(4)
/Users/josh/anaconda/envs/py27/lib/python2.7/site-packages/py4j/java_gateway.pyc in __call__(self, *args)
535 answer = self.gateway_client.send_command(command)
536 return_value = get_return_value(answer, self.gateway_client,
--> 537 self.target_id, self.name)
538
539 for temp_arg in temp_args:
/Users/josh/anaconda/envs/py27/lib/python2.7/site-packages/py4j/protocol.pyc in get_return_value(answer, gateway_client, target_id, name)
298 raise Py4JJavaError(
299 'An error occurred while calling {0}{1}{2}.\n'.
--> 300 format(target_id, '.', name), value)
301 else:
302 raise Py4JError(
Py4JJavaError: An error occurred while calling t.foo.
: java.lang.NoClassDefFoundError: company/sys/dao/ABCartDAO
at MyApplication.foo(MyApplication.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:231)
at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:379)
at py4j.Gateway.invoke(Gateway.java:259)
at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
at py4j.commands.CallCommand.execute(CallCommand.java:79)
at py4j.GatewayConnection.run(GatewayConnection.java:207)
at java.lang.Thread.run(Thread.java:744)
为什么?
万一这很重要,我正在构建我的java文件,其中包含以下内容pom.xml
<dependency>
<groupId>net.sf.py4j</groupId>
<artifactId>py4j</artifactId>
<type>jar</type>
<version>0.8.1</version>
</dependency>
我应该在我的.class
文件编译中包含一些额外的依赖项吗?这是一个错误Py4J
吗?也许是不受支持的功能?