我有 Java .jar 文件,它定义了几个类,并且有一个 python 框架,它打算从中选择任何类,实例化它的对象并调用它的方法。为此,我使用 py4j JavaGateway()。
在蟒蛇方面:
from py4j.java_gateway import JavaGateway
gateway = JavaGateway()
obj_rcvd = gateway.entry_point.getObj("pkg.in.jar", "className", java_list)
boo = pkg.in.jar.className(obj_rcvd)
"""
this typecast fails as python env doesn't know about pkg from jar. Can we import java's jar file in Python? Also if we can, do we really need to call JVM to get objects?
"""
在 Java 方面:
import py4j.GatewayServer;
import java.lang.reflect.*;
import java.util.*;
public class EntryPoint {
public static Object getObj(String pkgName, String className, List args) {
Object obj = null;
try {
Class cls2 = Class.forName(pkgName + '.' + className);
int num_of_args = args.size();
Class[] cArg = new Class[num_of_args];
Object[] cArg_val = new Object[num_of_args];
/* code to parse args to fill cArg and cArg_val */
Constructor ctor = cls2.getDeclaredConstructor(cArg);
obj = ctor.newInstance(cArg_val);
}
catch (ClassNotFoundException x) {
x.printStackTrace();
}
/* other exception catchers */
return obj; // this is general Object type, hence I need to typecast in python
}
public static void main(String[] args) {
GatewayServer gatewayServer = new GatewayServer(new EntryPoint());
gatewayServer.start();
System.out.println("Gateway Server Started");
}
我尝试从 Java 返回实际的类对象(硬编码用于调试的一种情况),但它也没有在 Python 中得到识别。请建议这种在python中调用java jar方法的方法是否可行。