java使用python_java调用python

1、一个可以和 Jython 对象映射的 Java 借口类

package com.newbee;

public interface EmployeeType {

public String getEmployeeFirst();

public String getEmployeeLast();

public String getEmployeeId();

public void setEmployeeId();

}

2、一个从 Jython 文件中获取 Java对象、Jython对象和 Jython函数对象的工厂方法类

package com.newbee;

import java.util.HashMap;

import org.python.core.PyFunction;

import org.python.core.PyObject;

import org.python.util.PythonInterpreter;

public class JythonFactory {

private static final JythonFactory instance = new JythonFactory();

private static final HashMap&ltString, PythonInterpreter&gt piMap = new HashMap&ltString, PythonInterpreter&gt();

public static JythonFactory getInstance() {

return instance;

}

public Object getJavaObjectFromJythonFile(String interfaceName, String pathToJythonModule) {

Object javaObject = null;

PythonInterpreter interpreter = cacheInterpreter(pathToJythonModule);

String tempName = pathToJythonModule.substring(pathToJythonModule.lastIndexOf("/") + 1);

tempName = tempName.substring(0, tempName.indexOf("."));

System.out.println(tempName);

String instanceName = tempName.toLowerCase();

String javaClassName = tempName.substring(0, 1).toUpperCase() + tempName.substring(1);

String objectDef = "=" + javaClassName + "()";

interpreter.exec(instanceName + objectDef);

try {

Class JavaInterface = Class.forName(interfaceName);

javaObject = interpreter.get(instanceName).__tojava__(JavaInterface);

} catch (ClassNotFoundException ex) {

ex.printStackTrace(); // Add logging here

}

return javaObject;

}

public PyObject getPyObjectFromJythonFile(String typeName, String pathToJythonModule) {

PyObject pyObject = null;

PythonInterpreter interpreter = cacheInterpreter(pathToJythonModule);

String instanceName = typeName.toLowerCase();

String objectDef = "=" + typeName + "()";

interpreter.exec(instanceName + objectDef);

pyObject = interpreter.get(instanceName);

return pyObject;

}

public PyFunction getPyFunctionFromJythonFile(String funcName, String pathToJythonModule) {

PyFunction pyFunction = null;

PythonInterpreter interpreter = cacheInterpreter(pathToJythonModule);

pyFunction = (PyFunction)interpreter.get(funcName,PyFunction.class);

return pyFunction;

}

private PythonInterpreter cacheInterpreter(String pathToJythonModule) {

PythonInterpreter interpreter = null;

if (piMap.get(pathToJythonModule)!=null) {

interpreter = piMap.get(pathToJythonModule);

} else {

interpreter = new PythonInterpreter();

int

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值