Home arrow Python arrow Page 3 - Introduction to Jython

Calling Java Classes - Python

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.

  1. Introduction to Jython
  2. Installing Jython
  3. Calling Java Classes
  4. Embedding
By: Peyton McCullough
Rating: starstarstarstarstar / 24
February 22, 2005

print this article



As I mentioned earlier, it is possible to call Java classes in Jython, which makes Jython extremely powerful. Anything that can be done in Java can be done in Jython using Python's easy syntax. Development time can also be significantly cut by accessing Java classes through Jython.

Let's play around with Java a bit. Using Swing in Java, it is fairly easy to create a simple dialog bearing a short message:

import javax.swing.JOptionPane;
class testDialog {
   public static void main ( String[] args ) {
      javax.swing.JOptionPane.showMessageDialog ( null, "This is a test." );

Using Jython, however, we can cut the amount of characters involved quite a bit. Save the following script, and pass its filename to the Jython interpreter:

import javax.swing.JOptionPane
javax.swing.JOptionPane.showMessageDialog ( None, "This is a test." )

As you can see, Python's syntax is used, but we're using a Java package. We don't have to compile anything, either. This speeds up the development process quite a bit, since we don't have to wait for the Java compiler each time we fix a small bug in our applications.

If you do not see the advantage to using Jython yet, let's convert a larger application from Java to Jython. We'll create a die roller in Java. The user will be able to specify how many sides the die has and select how many times he or she wishes to roll the die. The application will then generate random values within the appropriate ranges and present the results to the user.

import java.util.Random;
import javax.swing.JOptionPane;
class DieRoller {
   public static void main ( String[] args ) {
      System.out.println ( "Die Roller" );
      System.out.println ( "- - - - -" );
   public static void query () {
      String sidesS = JOptionPane.showInputDialog ( null, "How many sides should the die have?" );
      String rollsS = JOptionPane.showInputDialog ( null, "How many times should we roll the die?" );
      try {
          int sides = Integer.parseInt ( sidesS );
          int rolls = Integer.parseInt ( rollsS );
          roll( sides, rolls );
      } catch ( Exception e ) {
          JOptionPane.showMessageDialog ( null, "Error!" );
   public static void roll( int sides, int rolls ) {
      int current = 1;
      Random rand = new java.util.Random();
      while ( current <= rolls ) {
         System.out.println ( "Roll " + current + ": " + rand.nextInt ( sides ) );

Using Jython, we can reduce the number of lines in the application while accomplishing the same exact product:

import java.util.Random;
import javax.swing.JOptionPane;
print 'Die Roller'
print '- - - - -'
   sides = int ( javax.swing.JOptionPane.showInputDialog ( None, 'How many sides should the die have?' ) )
   rolls = int ( javax.swing.JOptionPane.showInputDialog ( None, 'How many times should we roll the die?' ) )
   rand = java.util.Random()
   for current in range ( rolls ):
      print 'Roll ' + str ( current + 1 ) + ': ' + str ( rand.nextInt ( sides ) )
   javax.swing.JOptionPane.showMessageDialog ( None, 'Error!' )

Notice how we replace the while loop with Python's for loop, which is more appropriate in this situation. In my opinion, the ability to use Python's for loop is a major advantage with Jython.

Of course, you are not restricted to building applications with Java. You can build servlets, beans and applets, too. Let's build a simple applet in Java to work with:

import java.applet.Applet;
class TestApplet {
   public void paint ( Graphics g ) {
      g.drawSring ( "A script a day keeps the doctor away.", 5, 5 );

Converting the application to Jython is very easy, and, again, we are left with the same product:

import java.applet.Applet;
class TestApplet ( java.applet.Applet ):
   def paint ( self, g ):
      g.drawString ( "A script a day keeps the doctor away.", 5, 5 )

Of course, we'll need to compile the applet before we can use it. This can be easily done:

jythonc -deep -core -compiler <compiler path> TestApplet.py

Compiling an application is just as easy.

It's also very possible and very simple to subclass an existing Java class. Subclassing a Java class is done in exactly the same way as subclassing a Python class. Let's modify the nextInt method of java.util.Random to return a string rather than an integer. To do the random number generation, we'll call the superclass's method:

>>> import java.util.Random
>>> class StringRandom ( java.util.Random ):
...    def nextInt ( self ):
...       return str ( java.util.Random.nextInt ( self ) )
>>> x = StringRandom()
>>> x.nextInt()
>>> x.nextInt()
>>> x.nextInt()

Since adding an attribute to an existing Java object is not possible in Jython, you are forced to create a subclass in Jython if you wish to add additional attributes:

>>> import java.util.Random
>>> rand = java.util.Random()
>>> rand.doesNotExist = 5
Traceback (innermost last):
  File "<console>", line 1, in ?
TypeError: can't set arbitrary attribute in java instance: doesNotExist
>>> class DumbyRandom ( java.utilRandom ):
...    pass
>>> rand = DumbyRandom()
>>> rand.doesNotExist = 5
>>> print rand.doesNotExist
>>> print rand.nextInt()

As you can see, the DumbyRandom class functions exactly the same as the Random class, except for the fact that we can add attributes to objects created from it.

>>> More Python Articles          >>> More By Peyton McCullough

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Python Big Data Company Gets DARPA Funding
- Python 32 Now Available
- Final Alpha for Python 3.2 is Released
- Python 3.1: String Formatting
- Python 3.1: Strings and Quotes
- Python 3.1: Programming Basics and Strings
- Tuples and Other Python Object Types
- The Dictionary Python Object Type
- String and List Python Object Types
- Introducing Python Object Types
- Mobile Programming using PyS60: Advanced UI ...
- Nested Functions in Python
- Python Parameters, Functions and Arguments
- Python Statements and Functions
- Statements and Iterators in Python

Developer Shed Affiliates


Dev Shed Tutorial Topics: