jython 一些认识

首页 http://www.jython.org/

具体安装过程略过~

文档 http://www.jython.org/jythonbook/en/1.0

在jython 2.5 后,取消了jythonc命令,可以用以下命令编译,但这个命令只能编译整个目录,指定文件还不行。
jython -m compileall path/to/your/jython/files',
最后会生成*$py.class文件。


org.python.core中有  java调用jython的几个核心类


package com.livefun.factory;

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 piMap = new HashMap();

	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("."));
		//tempName 是截取出的jython文件名
		String instanceName = tempName.toLowerCase();
		String javaClassName = tempName.substring(0, 1).toUpperCase() + tempName.substring(1);
		System.out.println("javaClassName" + javaClassName);
		String objectDef = "=" + javaClassName + "()";
		interpreter.exec(instanceName + objectDef);
		//相当于在interpreter中执行  name = jython函数名()

		try {
			Class JavaInterface = Class.forName(interfaceName);
			javaObject = interpreter.get(instanceName).__tojava__(JavaInterface);
			//从PythonInterpreter翻译器对象中拿到 jython模块的instanceName实例 然后转换成JavaInterface类型的java对象
		} 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();
		//instanceName 是为interpreter jython中的接口对象起得名字
		String objectDef = "=" + typeName + "()";
		interpreter.exec(instanceName + objectDef);
		//相当于在interpreter中执行  name = 接口名()

		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);
		//PyFunction.class 和 (PyFunction) 都可省略
		return pyFunction;
	}

	private PythonInterpreter cacheInterpreter(String pathToJythonModule) {
		PythonInterpreter interpreter = null;
		if (piMap.get(pathToJythonModule) != null) {
			interpreter = piMap.get(pathToJythonModule);
		} else {
			interpreter = new PythonInterpreter();
			interpreter.execfile(pathToJythonModule);
			//根据传入的jython模块文件转换成 interpreter 对象
			piMap.put(pathToJythonModule, interpreter);
		}
		return interpreter;
	}

}

 
  




你可能感兴趣的:(技术--java)