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

 
Developer Updates  
Free Website Content 
IBM Developerworks
 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? 
PYTHON

Introduction to Jython
By: Peyton McCullough
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 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:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb 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

    Route your faxes to your email inbox. Private, secure fax numbers available from CallWave. Choose your fax number.

    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


       · Nice =) Great subject, well written as usual
       · Is this real? Jython?
       · If you had read the article I don't think you'd be asking that question, but yes, it...
       · Thanks, David!I wrote this article because I find Jython extremely interesting....
       · I like the idea. I like python, especially for quick and dirty Unix tasks, like...
       ·  If you want to read how, see this...
       · Well, programming languages typically derive from the desire to complete a certain...
     

       

    PYTHON ARTICLES

    - SSH with Twisted
    - Mobile Programming in Python using PyS60: UI...
    - Python: Count on It
    - Python Strings: Spinning Yarns
    - Python: More Fun with Strings
    - Python: Stringing You Along
    - Python Operators
    - Bluetooth Programming in Python: Network Pro...
    - Python Sets
    - Python Conditionals, Lists, Dictionaries, an...
    - Python: Input and Variables
    - Introduction to Python Programming
    - Mobile Programming in Python using PyS60: Ge...
    - Bluetooth Programming using Python
    - Finishing the PyMailGUI Client: User Help To...

     
    Accelerating Trading Partner Performance
     
    Competing on Analytics
     
    Cost Effective Scaling with Virtualization and Coyote Point Systems
     
    Five Checkpoints to Implementing IP Telephony
     
    Hosted Email Security: Staying Ahead of New Threats
     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway