Java and Python -- each have their advantages and disadvantages. What is a programmer to do if he wants ease, efficiency, and power? Believe it or not, there is a solution -- a way to merge both languages and get the best of both worlds. Read on to find out how it works.
Jython allows us to embed Python code in Java code easily, and there are several approaches to it. The first is to use the PythonInterpreter object to execute Python code contained in a separate file. Let's create a Python file called "testCode.py" with the following code inside of it:
Execuing it in Java is simple using the execfile method:
import org.python.util.PythonInterpreter; import org.python.core.*; class TestPython { public static void main ( String[] args ) { try { org.python.util.PythonInterpreter python = new org.python.util.PythonInterpreter(); python.execfile ( "testCode.py" ); } catch ( Exception e ) { System.out.println ( "An error was encountered." ); } } }
We can also place code within the Java application itself using the exec method. Let's recreate our first example with the Python code included in the Java application rather than an external file:
We can also get and set variables in the local namespace by using the get and set methods. This allows us to interact with Python a bit more, which is our goal when embedding Python code inside Java applications:
Jython is an extremely powerful tool for development in both Python and Java. It allows you to use Python to call Java classes, increasing the power of Python, and it allows you to execute Python code inside Java applications by using the exec and execfile methods. Jython also allows you to subclass Java classes using Python. Jython can significantly decrease the effort needed to produce a powerful application, or even an applet, servlet or bean.
Of course, this article only covers the tip of the iceburg (forgive the cliché!). There is a lot more to Jython, but it would take a very lengthy article to cover all of it. It's up to you to explore more of Jython. Good luck!