py4j簡介:
官網
Py4J enables Python programs running in a Python interpreter to dynamically access Java objects in a Java Virtual Machine. Methods are called as if the Java objects resided in the Python interpreter and Java collections can be accessed through standard Python collection methods. Py4J also enables Java programs to call back Python objects.
Mac安裝:
- pip 安裝
pip install py4j
py4j.jar包路徑:/usr/share/py4j/py4j0.x.jar or /usr/local/share/py4j/py4j0.x.jar
- conda 安裝(或者使用Anaconda-Navigator安裝)
conda install py4j
py4j.jar包路徑:/anaconda3/share/py4j/py4j0.x.jar
使用:
1.java代碼
// 需要導入py4j.jar包
import py4j.GatewayServer;
import java.util.Random;
public class EntryPoint {
private static final Random random = new Random();
public int randInt() {
return random.nextInt();
}
public static void main(String[] args) {
EntryPoint app = new EntryPoint();
// py4j服務
GatewayServer gatewayServer = new GatewayServer(app);
gatewayServer.start();
System.out.println("Gateway Server Started");
}
}
2.Python代碼
from py4j.java_gateway import JavaGateway
# 初始化
gateway = JavaGateway()
def main():
# 調用Java-EntryPoint中的randInt函數
a = gateway.entry_point.randInt()
print(a)
if __name__ == '__main__':
main()
注意:
1.導入py4j.jar包
2.運行Java代碼
3.運行Python代碼(必須在2之后)
python調用Java的其他方式:
感謝ayuLiao的這篇文章python調用Java的多種方法