我最近发现py4j并且能够从python调用静态java方法。现在我想从java调用python方法。我找不到太多的文档,所以这是我能想到的最后一个地方,可能会告诉我是否可能,以及如何。
答案 0 :(得分:6)
您可以通过implementing a Java interface on the python side从Java调用Python方法。
步骤如下:
gateway = JavaGateway(start_callback_server=True)
改编自Py4J文档的示例:
Java代码:
// 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<Integer> randomBinaryOperator(Operator op) {
Random random = new Random();
List<Integer> numbers = new ArrayList<Integer>();
numbers.add(random.nextInt(MAX));
numbers.add(random.nextInt(MAX));
numbers.add(op.doOperation(numbers.get(0), numbers.get(1)));
return numbers;
}
}
Python代码:
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)