我正在使用py4j进行python和java之间的通信。我可以从java端调用python方法。但是从 python 我无法发送任何对象或调用 java 方法。这是我尝试过的代码。
我的java
代码:
public interface IHello {
public String sayHello();
public String sayHello(int i, String s);
// public String frompython();
}
//ExampleClientApplication.java
package py4j.examples;
import py4j.GatewayServer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ExampleClientApplication extends Thread {
public void run(){
System.out.println("thread is running...");
}
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
GatewayServer.turnLoggingOff();
GatewayServer server = new GatewayServer();
server.start();
IHello hello = (IHello) server.getPythonServerEntryPoint(new Class[] { IHello.class });
try {
System.out.println("Please enter a string");
String str = br.readLine();
System.out.println(hello.sayHello(1, str));
} catch (Exception e) {
e.printStackTrace();
}
ExampleClientApplication t1 = new ExampleClientApplication();
t1.start();
//server.shutdown();
}
}
我的python代码:
class SimpleHello(object):
def sayHello(self, int_value=None, string_value=None):
print(int_value, string_value)
return "From python to {0}".format(string_value)
class Java:
implements = ["py4j.examples.IHello"]
# Make sure that the python code is started first.
# Then execute: java -cp py4j.jar
py4j.examples.SingleThreadClientApplication
from py4j.java_gateway import JavaGateway, CallbackServerParameters
simple_hello = SimpleHello()
gateway = JavaGateway(
callback_server_parameters=CallbackServerParameters(),
python_server_entry_point=simple_hello)