博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Accessing Jython from Java Without Using jythonc
阅读量:6836 次
发布时间:2019-06-26

本文共 5444 字,大约阅读时间需要 18 分钟。

Accessing Jython from Java Without Using jythonc

  

Submitted By: Josh Juneau   

You may or may not know that it is possible to access Jython code from Java without compiling it using the jythonc utility. This technique is possible using a mixture of Java interfaces and usage of the . As a matter of fact, I believe that using this technique correctly is more effective than using jythonc.   

To put it simply, to use this technique you must create a "factory" method which uses the class to interpret a .py module for use within Java code. Any Java code that uses the Jython code should be coded against an interface which is implemented by the Jython code.   

In order to provide a fully functional example, I've created a simple application with hard-coded data. This application shows the potential for using this technique within your Java applications to have the ability for use of dynamic Jython objects.  

The application is simply called "jyinterface" and it contains four pieces of code:

  • -Main.java

    -.java - Uses the to return a Java object

    -.java - An interface which will be implemented by a Jython bean -Employee.py - Jython bean representing an employee

We'll start by coding the ".java" interface which is what our Java code will use in order to interact with the Jython object:

 

package jyinterface.interfaces;public interface EmployeeType {    public String getEmployeeFirst();    public String getEmployeeLast();    public String getEmployeeId();}

 

The Jython bean "Employee.py" is just a simple Jython object which implements the Java interface ".java":

 

# Jython source filefrom jyinterface.interfaces import EmployeeTypeclass Employee(EmployeeType):   def __init__(self):      self.first = "Josh"      self.last  = "Juneau"      self.id = "myempid"   def getEmployeeFirst(self):      return self.first   def getEmployeeLast(self):      return self.last   def getEmployeeId(self):      return self.id

 

Next, the most powerful code for this technique is the ".java" class. This code defines a method which interprets a Jython module into Java and returns for use within Java code. The best part about creating a factory class such as this one is reuse! The factory can be coded in many different ways, but this way allows for reuse because you can essentially pass any Java interface/Jython module to it.

 

package jyinterface.factory;import org.python.util.PythonInterpreter;public class JythonFactory {   private static JythonFactory instance = null;   public synchronized static JythonFactory getInstance(){        if(instance == null){            instance = new JythonFactory();        }        return instance;    }   public static Object getJythonObject(String interfaceName,                                        String pathToJythonModule){       Object javaInt = null;       PythonInterpreter interpreter = new PythonInterpreter();       interpreter.execfile(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);           javaInt =                interpreter.get(instanceName).__tojava__(JavaInterface);        } catch (ClassNotFoundException ex) {            ex.printStackTrace();  // Add logging here        }       return javaInt;   }}

 

As we stated previously, a Java interface/Jython module combo needs to be passed to the getJythonObject method in order to return the resulting code. In the following piece of code, you can see how this is done. Simply pass in two strings:

  1. Fully qualified name of the Java Interface
  2. Full path to the Jython code module

Here is the "Main.java" code:

 

package jyinterface;import jyinterface.interfaces.EmployeeType;import jyinterface.factory.JythonFactory;import org.python.util.PythonInterpreter;public class Main {    EmployeeType et;    /** Creates a new instance of Main */    public Main() {    }    /**     * @param args the command line arguments     */    public static void main(String[] args) {        JythonFactory jf = JythonFactory.getInstance();        EmployeeType eType = (EmployeeType) jf.getJythonObject(                               "jyinterface.interfaces.EmployeeType", "<
>/Employee.py"); System.out.println("Employee Name: " + eType.getEmployeeFirst() + " " + eType.getEmployeeLast()); System.out.println("Employee ID: " + eType.getEmployeeId()); }}

 

This technique is powerful because it allows an application to use code which can be interchanged or dynamically updated without re-deployment or re-compile. It also follows a great Java practice which is code against Java interfaces!! One downfall to this approach is that the code is interpreted every time it is invoked, so the performance may not be as good as using a jythonc compiled piece of code. It obviously depends upon the requirements of the application, but the usefulness of this technique may outweigh the performance factor in many cases.

Next time you plan to create a Java application that contains some Jython code, give this technique a try...

转载地址:http://xmqkl.baihongyu.com/

你可能感兴趣的文章
策略模式
查看>>
通过tomcat实现多域名配置
查看>>
JAVA实现环形缓冲多线程读取远程文件
查看>>
#Note# 极客与团队-软件工程师的生存秘笈
查看>>
redis的观察者模式----------发布订阅功能
查看>>
JDBC连接SQLserver2008,使用jdk为1.7 [个人新浪微博]
查看>>
ps、磨皮、修改图片
查看>>
SpringCloud动态刷新配置信息
查看>>
Spring Boot 注册 Servlet 的三种方法,真是太有用了!
查看>>
ThreadLocal 简介
查看>>
vs2010 使用STLport-5.2.1
查看>>
LVS三种工作模式介绍对比和十种调度算法介绍
查看>>
tvOS模拟器遥控的快捷键
查看>>
替换libc中的内存分配函数
查看>>
myeclipse8.6安装svn
查看>>
序列化和反序列化二叉搜索树 Serialize and Deserialize BST
查看>>
批量去除歌曲tag标签
查看>>
驰骋工作流引擎设计系列05 启动流程设计
查看>>
Java 启动线程并保持
查看>>
CentOS7使用firewalld打开关闭防火墙与端口
查看>>