py4j

2022-03-17  本文已影响0人  hehehehe

python -> java

from py4j.java_gateway import JavaGateway

if __name__ == '__main__':
    gateway = JavaGateway()
    a = gateway.entry_point.randInt()
    print(a)
    print(gateway.entry_point.helloWorld())
    print(gateway.entry_point.returnList())
    arrayList = gateway.jvm.java.util.ArrayList()
    arrayList.add(3)


package ogr.test;

import py4j.GatewayServer;

import java.util.ArrayList;
import java.util.Random;

public class Py4jTest {

    private static final Random random = new Random();

    public int randInt() {
        return random.nextInt();
    }

    public String helloWorld() {
        return "Hello World";
    }

    public ArrayList<String> returnList() {
        return new ArrayList<String>() {
            {
                add("1");
                add("2");
            }
        };
    }

    public static void main(String[] args) {

        Py4jTest app = new Py4jTest();
        // py4j服务
        GatewayServer gatewayServer = new GatewayServer(app);
        gatewayServer.start();
        System.out.println("Gateway Server Started");
    }
}


java -> python

package ogr.test;

public interface IHello {
    public String sayHello();

    public String sayHello(int i, String s);
}



package ogr.test;

import py4j.GatewayServer;

public class ExampleClientApplication {
    public static void main(String[] args) {
        GatewayServer.turnLoggingOff();
        GatewayServer server = new GatewayServer();
        server.start();
        IHello hello = (IHello) server.getPythonServerEntryPoint(new Class[]{IHello.class});
        try {
            System.out.println(hello.sayHello());
            System.out.println(hello.sayHello(2, "Hello World"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        server.shutdown();
    }
}
class SampleHello(object):

    def sayHello(self, int_value=None, string_value=None):
        print(int_value, string_value)
        return "Said hello to {0}".format(string_value)

    class Java:
        implements = ["py4j.examples.IHello"]


if __name__ == '__main__':
    from py4j.java_gateway import JavaGateway, CallbackServerParameters

    simple_hello = SimpleHello()
    gateway = JavaGateway(
        callback_server_parameters=CallbackServerParameters(),
        python_server_entry_point=simple_hello)

上一篇 下一篇

猜你喜欢

热点阅读