Tips for scripting java with jython

zhaozj2021-02-16  73

http://www.onjava.com/pub/a/onjava/2002/03/27/jython.html

Tips for scripting java with jython

By Noel Rappin, Co-Author of Jython Essentials

03/27/2002

YOU HAVE A Programming Dilemma.

Maybe you're writing a Java program, and you need to do a quick one-off script to clean up your database. Sure, you could write it in Java, but that can involve a lot of overhead for a quick script. You could Write It in An Outside Scripting Language, But You'd Really Like Access To The Business Logic Already in Your Java Program.

OR Maybe You're Writing a Servlet, And The Requirements Are Changing Quickly. Your Data Model Is Changing, and You're Having Trouble Keeping All The Type Information.

Or maybe you're writing a standalone program, and you'd like to use the large variety of tools already written for Java, but you'd also like to use a tool that makes your program 25-50 percent shorter, and easier to Write and maintain.

Jython is the Tool for you.

Jython is a complete re-implementation of the Python programming language, written in 100 percent pure Java, which runs on any Java Virtual Machine (JVM). Python is a high-level, interpreted, object-oriented scripting language which combines elegant syntax rules WITH POWERFUL BUILT-IN Objects to create a Language That Is Very Easy to Write, Read, And Maintain. Python IS Perhaps Most Notorious for ITS Use of Indentation To Mark The Beginning and End of Statement Blocks.

There Are Usually Two Reactions To this Description of Jython. Some People ASK, "Does It Really Work?"

It really works. Anything you can do with the Java SDK can be done in Jython, including standalone applications, applets, servlets, and beans. Arbitrary Java code can be called from Jython, Java objects can be used as-is, or can be subclassed in Jython. You can even write an object in Jython that can be used or subclassed by other Java code. in addition, nearly all of the modules of the standard Python library are available to be used from Jython.Another common reaction is to ask why Jython is needed, since Java already exists. Java, like every programming language, is a tool, and it has its uses. But it can not be all things to all people. Outside of the Java world, you can use C / C , Python, Perl, or any of dozens of Other Languages, Each With ITS OWN Stregths and weakness. Jython Gives Some of the Same Flexibility To The Java Programmer.

Here Are 11 Specific Features of Jython That Can Be Particular Time-Saving or Exciting for Java Program.

INTERACTIVE INTERPRETER

The Jython interpreter can run in an interactive mode. In this mode you can type in Jython code one line at a time and see the results. You can even interact with Java libraries via this interpreter. For example, if you type the following at the JYTHON PROMPT:

>>> Import javax.swing as swing

>>> Win = swing.jframe ("Welcome to Jython")

>>> win.size = (200, 200)

>>> Win.SHOW ()

Jython will create a swing JFrame and display it on screen. You can continue to view and modify the attributes of the JFrame via the prompt. This can be tremendously useful during prototyping or while debugging. (You've probably noticed what seem to be some TYPE INCONSISTENCIES in The Third Line of That Code - for More On Tip # 9) .2. Built-in Data Structures

The Jython analogues to Java's collection classes are much more tightly integrated into the core language, allowing for more concise descriptions and useful functionality For example, notice the difference between the Java code.:

Map = new hashmap ();

Map.Put ("One", New Integer (1));

Map.Put ("Two", New Integer (2));

Map.Put ("Three", New Integer (3));

System.out.println (Map.get ("one"));

List = new linkedList ();

List.add (new integer (1));

List.add (new integer (2));

List.add (new integer (3));

And the Jython Code:

Map = {"One": 1, "Two": 2, "Three": 3}

Print Map ["one"]

List = [1, 2, 3]

Jython's for Statement IS Dependent on the list Structures, SO if you wanted to iterate over the Above list, you would Write IT:

For i in list:

Which is Just A Bit Simpler Than The Java IDiom for ITERATING OVER A LIST:

ITerator I; I.hasNext ();) {

i.next ();

}

In Jython, The for Statement Will Also Automatically Iteerate Over Java Lists, Arrays, Iterators, and Enumerators.

3. List comprehensions

Jython Offers List Comprehensions, Which Are A Cool Shortcut for The Common Task of Creating A List by Applying A Specific Function To Each Element of An Existing List. For Example, in Jython You CAN Write:

Newlist = [Function (i) for i in in oldlist]

Which is essentially equivalent to the java code: List newlist = arraylist ()

ITerator I; I.hasNext ();) {

Object obj = i.next ();

NewList.Add (Function (OBJ));

}

List comprehensions can also provide a filteriff.

-------------------------------------------------- ------------------------------

Related recaps

Jython Essentials

By Samuele Pedroni, NOEL RAPPIN

Table of contents

Index

Sample chapter

-------------------------------------------------- ------------------------------

4. Dynamic Variable Creation

In Jython, variables do not have to be declared before use, nor do their types need to be declared. (They do, however, have to be assigned before use). This is true both for local variables within a block, and for the Data Members of classes. Jython IS, HOWEVER, STILL STRONGLY TYPED, AND LIKE JAVA, WILL NOTOTOMATILY CARIABLE TYES. Attempting to do Something Like:

1 "1"

Will Raise An Exception in Jython At Runtime.

If you have never programmed in a dynamic language, it is understandable that the idea of ​​not declaring variables or types may make you a little nervous. Programmers who switch to a dynamic language are often surprised by how rarely type errors actually occur in practice, and how quickly they are found and fixed when they do occur. When compared with the amount of effort spent in Java convincing the compiler that your program is legal, you may find that static typing may not always be worth the effort.

Pages: 1, 2

Tips for scripting java with jython

Pages: 1, 2

5. First Class Functions

In Jython, functions, methods, modules, and classes are all first class objects, which means they can be both passed to and returned from a function. This ability allows for some common programming tasks to be managed quite easily.For example, suppose you have a complicated resource that needs to be opened, used, and closed in a variety of places, which might cause you to retype the open and close logic frequently. A simple example is a file. By passing the useful function as a parameter you can Manage the resource in One Place:

DEF FileLinesDO (FileName, Linefunc):

FILE = Open (filename, 'r')

Result = [Linefunc (EACH) for each in file.readlines ()]

File.close ()

Return RESULT

The key here is that you do not have to rewrite the open and close statements each time you use the file, you can just call fileLinesDo. This is a trivial point for files, but if we added error checking or had a more complicated resource , IT Becomes Very Useful.

6. Dynamic Object-Oriented Typing

In Java, the legality of a method call such as obj.method () is calculated at compile time. Although this ensures that the method will exist at runtime, in practice it leads to a lot of time and effort spent on typecasts. It also .

Myclass instance = (myclass) list.get (2);

In Jython, the legality of obj.method () is determined at runtime based on the runtime type of the obj variable. In addition to removing the need for a typecast, this has several subtle benefits. Most importantly, it encourages reuse by making it . easier to use an object of a different type in the existing code This eliminates the need to define Java-style interfaces; instead you can just define the methods directly.It also allows for old code to be used in ways not imagined when the code was written. Additionally, it makes Jython code much easier to unit test than Java code (and it also makes it easy to unit test Java code from Jython). In Jython, you can easily create a simple "mock object" that trivially responds to The Methods of a Hard- Or Expensive-To-create Instance (Such as a gui or database), and use what to test your code.

7. Special Methods

Jython allows operator overloading in the form of specially named methods that can be defined on any object, and which are called by the interpreter, if they exist, when the corresponding core language function or operator is invoked.

Some of these are quite similar to Java functionality, such as the special method __str__, which is called when the object needs to be printed, and is equivalent to the Java toString (). Others, such as the __add__ method, are similar to operator OverLoading In C . You can allow your instances to be acceptible using array-like syntax using the __getitem__ and __setitem__methods.

Other special methods allow an amazing amount of flexibility for your objects. The special method __getattr__ is called on any failed attribute lookup, and can be used, for example, to return a default value, or automatically redirect to a proxy object, or call a getter method. The special method __setattr__ is called on attribute assignment, and can be used, for example, to verify values, or to trivially broadcast changes to other interested objects. There is even a special method __call__, which allows your instances to be treated Like functions.8. java integration

Most of the features discussed above are features of the Python language, but Jython also has features that allow nearly transparent usage of existing Java code. Java packages can be imported into Jython as though they were Jython modules, and Java objects can be created using Jython Object Creation Syntax. for the Most Part, You CAN Use The Java Objects in your Jython Program Exactly as wegh They WERE JYTHON Objects (As Shown In Tip # 1).

Jython classes can inherit from Java classes (Jython allows multiple inheritance of Jython classes, however no more than one Java class can be in the inheritance tree of a Jython object) The inheritance rules work essentially as you would expect -. The parent class Java methods are called if they are not overridden in the child class. If the parent class method is overloaded, Jython chooses the correct version of the method based on the signature of the arguments at runtime.

9. Bean Property Introspection

Jython uses introspection on Java objects to allow access to those objects in a more normal Python coding style. Python coders rarely use simple get and set methods, preferring to access the variable directly. Of course, Java style tends to encourage get and set methods. Jython Introspection Allows Those Calls to Be Made Automatically. When Jython SEES a line of code such as: x = javaobj.attribute

IT Automatically Generated Java Call of the Method Javaobj.getaTRibute (), IF Such A Method Exists. Similarly, An Assignment To Javaobj.attribute Is Converted To A Call To Javaobj.setttribute.

In Addition, SET METHODS CAN Be Automatically Triggered from Constructors by Using A Keyword Argument. For example:

Javax.swing.jprogressbar (StringPainted = 1, Foreground = color.green)

automatically invokes the setStringPainted () and setForeground () methods of the new JProgressBar instance - even though the normal Java constructor for JProgressBar does not take arguments for these properties.

If the set method itself takes an instance argument, Jython lets you implicitly create an object of the needed class by placing the arguments to the constructor sequentially in a list on the right side of the assignment (technically, the structure in Jython is called a tuple And is an immutable list). for example:

Button.preferredsize = (300, 50)

Calls the Java Code

Button.SetPreferRedsize (New Dimension (300, 50))

10. Event Listener Introspection

Jython also automatically performs introspection on event listener registration patterns and interfaces. When a Java class allows listeners to be registered for a bean event, Jython searches for the listener interface associated with that event.

When an instance of the class is created, Jython adds an additional attribute for each method defined by the interface. Since Jython has first class functions, you can directly assign a Jython function to those attributes, and Jython calls that function when the event is triggered This allows you to replace Java Inner Classes with Ordinary Methods for Responding to Events.The Following Java Code Uses Inner Classes To Terminate The Program in Response To a Button Push:

JButton Close = New JButton ("Close Me");

Close.AddActionListener (New ActionListener () {

Public void actionperformed (ActionEvent EVT) {

Java.lang.system.exit (0);

}

});

The Jython equivalent uses Jython introspection to separate the function definition from the widget creation. It creates a separate function, terminateProgram (), and passes that to the JButton to be called when the action is performed. This code assumes that the JButton is defined inside a class.

Close = swing.jbutton ("Close Me", ActionPerformed = Self.TerminateProgram)

DEF TERMINATEPROGRAM (Self, Event):

Java.lang.system.exit (0)

The combination of property and event introspection makes Java libraries extremely easy to use from Jython. Swing code, for example, is significantly easier to read and manage because of the use of the Jython shortcuts.

11. Embedding

The easiest way to include Jython functionality into an existing Java program is to embed a Jython interpreter directly into the Java code. The Jython interpreter is a Java object, and an instance of the interpreter can be used within a Java program to evaluate Jython code. The Java Program CAN Interact with the Jython Interpreter, And Pass Data Back and Forth Between The Two.

The embedded interpreter can be used to manage various kinds of customization of the parent program. For example, you could write a system management framework that allows users to define responses to system events in Jython. Property files could be written as live Jython modules. You could create programmatic filters with all the power of the Python language to enhance, for example, an email client. You could use Jython for macro functionality in nearly any kind of program, or as a mechanism to separate game logic from a game engine.This is a very straightforward way of getting the benefits of Jython on an existing Java project. in fact, Jython servlets are written in this manner, with a pre-existing Java servlet which reads the Jython servlet in an embedded interpreter.

I Hope this List Has Encouraged You To Seek Out Jython and Try IT YOUR JVM-BASED PROJECTS. For more information get a copy of jython essentials. Jython Can Be Downloaded from Jython.org.

Noel Rappin Has Extensive Production Experience In Both Java and Python.

转载请注明原文地址:https://www.9cbs.com/read-16299.html

New Post(0)