Python
  Home arrow Python arrow Page 3 - Introduction to Jython
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PYTHON

Introduction to Jython
By: Peyton McCullough
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 21
    2005-02-22


    Table of Contents:
  • Introduction to Jython
  • Installing Jython
  • Calling Java Classes
  • Embedding

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Introduction to Jython - Calling Java Classes
    ( Page 3 of 4 )

    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 ( "- - - - -" );
          query();
       }
       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 ) );
             current++;
          }
       }
    }

    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 '- - - - -'
    try:
       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 ) )
    except:
       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()
    '834361961'
    >>> x.nextInt()
    '159629831'
    >>> x.nextInt()
    '-1197591800'

    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
    5
    >>> print rand.nextInt()
    -1884599813

    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
     

       

    PYTHON ARTICLES

    - 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
    - Sequences and Sets in Python
    - Python Expressions and Operators
    - Dictionaries, Variables and Statements in Py...
    - Data Types in Python
    - The Python Language
    - SSH with Twisted





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek