哪个网站可以做照片分享,宁波自助建站网站,seo关键词优化推广,普通的旧房装修价格java中使用jythonJython是一个使用相当可靠的语法的快速Java脚本的好工具。 实际上#xff0c;当使用jmx为您的Java应用程序实现一些维护或监视脚本时#xff0c;它的运行效果非常好。 如果您与其他具有python背景的团队合作#xff0c;则将python集成到您的java应用程序是… java中使用jython Jython是一个使用相当可靠的语法的快速Java脚本的好工具。 实际上当使用jmx为您的Java应用程序实现一些维护或监视脚本时它的运行效果非常好。 如果您与其他具有python背景的团队合作则将python集成到您的java应用程序是绝对有意义的。 首先让我们使用独立版本导入jython interpeter。 group com.gkatzioura
version 1.0-SNAPSHOTapply plugin: javasourceCompatibility 1.5repositories {mavenCentral()
}dependencies {testCompile group: junit, name: junit, version: 4.11compile group: org.python, name: jython-standalone, version: 2.7.0
} 因此最简单的方法就是在我们的类路径中执行python文件。 该文件将是hello_world.py print Hello World 然后将文件作为输入流传递给干预者 package com.gkatzioura;import org.python.core.PyClass;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.core.PyObjectDerived;
import org.python.util.PythonInterpreter;import java.io.InputStream;/*** Created by gkatzioura on 19/10/2016.*/
public class JythonCaller {private PythonInterpreter pythonInterpreter;public JythonCaller() {pythonInterpreter new PythonInterpreter();}public void invokeScript(InputStream inputStream) {pythonInterpreter.execfile(inputStream);}}Testpublic void testInvokeScript() {InputStream inputStream this.getClass().getClassLoader().getResourceAsStream(hello_world.py);jythonCaller.invokeScript(inputStream);} 下一步是创建一个python类文件和另一个将导入该类文件并实例化一个类的python文件。 该类文件将是divider.py。 class Divider:def divide(self,numerator,denominator):return numerator/denominator; 导入Divider类的文件将是classcaller.py from divider import Dividerdivider Divider()print divider.divide(10,5); 所以让我们测试一下 Testpublic void testInvokeClassCaller() {InputStream inputStream this.getClass().getClassLoader().getResourceAsStream(classcaller.py);jythonCaller.invokeScript(inputStream);} 从这个例子中我们可以理解的是解释器成功地从类路径中导入了文件。 使用解释器运行文件是可以的但是我们需要充分利用python中实现的类和函数。 因此下一步是创建一个python类并使用java使用其功能。 package com.gkatzioura;import org.python.core.PyClass;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.core.PyObjectDerived;
import org.python.util.PythonInterpreter;import java.io.InputStream;/*** Created by gkatzioura on 19/10/2016.*/
public class JythonCaller {private PythonInterpreter pythonInterpreter;public JythonCaller() {pythonInterpreter new PythonInterpreter();}public void invokeClass() {pythonInterpreter.exec(from divider import Divider);PyClass dividerDef (PyClass) pythonInterpreter.get(Divider);PyObject divider dividerDef.__call__();PyObject pyObject divider.invoke(divide,new PyInteger(20),new PyInteger(4));System.out.println(pyObject.toString());}} 您可以在github上找到源代码。 翻译自: https://www.javacodegeeks.com/2016/10/embed-jython-java-codebase.htmljava中使用jython