java如何调用python接口,py4j - 我将如何在java中调用python方法

I've recently discovered py4j and was able to call static java methods from python. Now I want to call python methods from java. I couldn't find much documentation so this is the last place I can think of that might tell me if it's possible, and how.

解决方案

The steps are:

Create an interface in Java, e.g., py4j.examples.Operator

In Python, create a class and inside the class, create a Java class with an "implements" field.

In Python, instantiate a gateway with start_callback_server=True, e.g., gateway = JavaGateway(start_callback_server=True)

In Python, instantiate the class implementing a Java interface and send it to the Java side.

In Java, call the interface.

Example adapted from the Py4J documentation:

Java code:

// File 1

package py4j.examples;

public interface Operator {

public int doOperation(int i, int j);

public int doOperation(int i, int j, int k);

}

// File 2

package py4j.examples;

import java.util.ArrayList;

import java.util.List;

import java.util.Random;

import py4j.GatewayServer;

public class OperatorExample {

// To prevent integer overflow

private final static int MAX = 1000;

public List randomBinaryOperator(Operator op) {

Random random = new Random();

List numbers = new ArrayList();

numbers.add(random.nextInt(MAX));

numbers.add(random.nextInt(MAX));

numbers.add(op.doOperation(numbers.get(0), numbers.get(1)));

return numbers;

}

}

Python code:

from py4j.java_gateway import JavaGateway

class Addition(object):

def doOperation(self, i, j, k = None):

if k == None:

return i + j

else:

return i + j + k

class Java:

implements = ['py4j.examples.Operator']

if __name__ == '__main__':

gateway = JavaGateway(start_callback_server=True)

operator = Addition()

operator_example = gateway.jvm.py4j.examples.OperatorExample()

# "Sends" python object to the Java side.

numbers = operator_example.randomBinaryOperator(operator)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值