greenflute 发表于 2006-9-7 10:40

[Link]Java Scripting Gets Groovy

Java Scripting Gets Groovy
A dynamic Java-like syntax for the JVM seeks to be the first standardized scripting language for Java
by Daniel F. Savarese

Few programming experiences are as frustrating as squandering hours trying to fix a bug in your code only to find that the bug instead lies in a compiler or run-time library. When I was a teaching assistant in graduate school, invariably undergraduates would blame the compiler when they ran into an unusual behavior instead of carefully debugging their code. Although it was not unheard of for a compiler to produce bad code at times, I would encourage students to be more systematic and exhaustive in their debugging efforts before exploring the possibility of a flaw in the compiler. That was before Java. My early Java experiences were fraught with fighting bugs in the JDK libraries and the first generation of just-in-time (JIT) compilers. Every time I think those days are over, I either hear a story about JIT problems or run headlong into another Java fiasco.

My most recent bad experiences have been caused by the java.nio libraries in J2SE 1.4. There have been several problems with the java.nio implementation on multiple platforms in each 1.4 release including the latest 1.4.2_04 SDK. To make a long story short, even though other java.nio bugs have been resolved, selectable I/O with nonblocking connects does not work. Don't waste your time. Shame on me for using Java for network systems programming. Different manifestations of the bug have been reported on the Java Bug Parade (see Resources), but it has gone unfixed since at least September 2003.

I've never been a vocal proponent of open sourcing Java, although I have been vocal about opening up the Java Community Process (JCP). My most recent bug experience has convinced me that Sun needs to open source Java and make it easy for Java developers to fix their problems and submit patches. I'm not claiming the following is a trend, but I'm not the only programmer increasing his use of alternatives to Java such as Python on the server and its wxPython offshoot on the client. I long ago relegated Perl for use in short programs because of software maintenance difficulties, but Perl 6 may change that. This is all to say that scripting languages supply Java's cross-platform programming capability and have done nothing but increase in popularity as Moore's law has remedied their performance deficiencies.

Not Another One!
The number of scripting languages available to programmers grows every year. Programmers like scripting languages because they are easy to learn, provide high-level functionality that reduces the time to develop programs, and often can be used to glue together disparate program components. Java has seen its share of scripting languages and tools. A sampling includes Jython, Jacl, NetRexx, Rhino, BeanShell, JRuby, JudoScript, BSF, and Swig. The latter two are tools for embedding scripting languages in programs and enabling interlanguage communication. Despite all of the options available already, an open source project called Groovy (see Resources) has submitted JSR 241 to the JCP seeking to make Groovy the first standardized scripting language for Java.

The question that programmers ask immediately upon learning of Groovy is "Why do we need yet another scripting language?" It's difficult to justify creating yet another scripting language, especially when it shares so many of the same features as other scripting languages. A persuasive argument made by the Groovy development team is that other scripting languages, like Python, have a syntax dissimilar to Java, and when adapted to Java, like Jython, they attempt to recreate all of the standard libraries of the parent language instead of relying on Java's core libraries. Groovy maintains a syntax close to Java's, but incorporates significant differences. It also builds on Java's standard libraries and compiles to byte code, making it easy to combine with

The documentation for Groovy is still incomplete and does not explain how everything works. That's where the language specification to be produced by JSR 241 will come in handy. Right now there's a certain amount of trial and error involved in writing Groovy scripts, although you can always look at the Groovy source code or avail yourself of the Groovy developer and user mailing lists for help. A good way to get acquainted with a new language is to dive in with some examples. Listing 1 contains a Java program that paints a black-and-white checkerboard of adjustable size in a window. It is based on the SwingBoard example from my column, "Eclipse vs. Swing" (Java Pro, December 2002). Listing 2 contains a Groovy script implementing the same program. Let's examine their differences.

You'll notice a couple of differences immediately. Groovy does not require semicolons. They are optional. Groovy does not require an encapsulating class and static main method to execute a program. Again, that's optional. The GroovyCheckerboard script is compiled into a class called GroovyCheckerboard with a static main method containing the main script. Primitive types are not used in Groovy. All constants are autoboxed, and if you declare the type of what would normally be a primitive variable, you must use the primitive wrapper classes from the java.lang package—such as Integer and Boolean. I say "if you declare the type" because Groovy is dynamically typed. You do not have to declare the type of a variable; it is determined upon assignment. However, you must declare a variable before it is used, as when frame is declared before use in the listener closure (see Listing 2).

Feeling Groovy
All class and member declarations are automatically public. If you want to restrict access to a class or member, you must declare it as either protected or private. However, public and protected variables are not accessed directly. They are transformed into private variables with corresponding public or protected getter and setter methods. Therefore every Groovy object is a JavaBean, and its members are properties. Even though the Groovy syntax for accessing a member variable is the same as in Java, the syntax:


object.property = value


is transformed into:


object.setProperty(value)


At the same time, Java objects with setter and getter methods are treated as JavaBeans with accessible properties, which is why you can write:


frame.visible = true


instead of:


frame.setVisible(true)


as well as initialize board by treating boardSize as a property (see Listing 2). You can do most things in Groovy as you would in Java, but then there's also the Groovy way (sometimes more than one Groovy way). This ability to use different syntactic forms to perform the same operation may make Groovy scripts difficult to understand. Perl's "more than one way to do it" philosophy has proven both boon and bane. Those who find it banal often migrate to Python.

Two of the features you will find most useful in Groovy are native syntax for lists and maps and support for closures. Support for lists and closures raises the same question more than one scripting language has elicited: "Why aren't we all programming in Lisp or Scheme?" (Return statements are also optional in Groovy.) It would certainly reduce the motivation for continuing to develop new scripting languages. Groovy lists support several operations that make them easy to work with. For example, this use of a list and a closure will print every element of the list:


[ "hunt", "the", "wumpus" ].each
{ println it }


Oh yes, parentheses in method calls such as the invocation of println are optional. Similarly, this will print each key and value of a map:


[ "instrument" : "guitar" ,
"model" : "Les Paul Custom"
].each { println "key:
${it.key} value: ${it.value}"
}


Yes, you can embed variables in strings as in the argument to println.

The closures in the previous two examples use an implicit parameter called it. You can also declare the parameters of closures as in the assignment to listener (see Listing 2). If you are familiar with Lisp, a closure is like a lambda expression. The closest thing in Java to a closure is an anonymous inner class. Groovy closures are true closures in the sense that they allow local variables outside of the closure to be used inside of the closure and if you return a closure from a function, it will be a different instance every time using variable bindings specific to the local context of the function call. Also, closures are implemented as objects that can be instantiated and assigned to variables.

Groovy Markup
There's a lot more to Groovy than I've mentioned, including stand-alone functions, dynamic method dispatch, default method parameters (as in setBoardSize in Listing 2), and path expression syntax. In the end though, Groovy's utility will not be measured by how many features it packs, but by how much time it saves you. It is advantageous that Groovy can call Java objects and be embedded easily in Java programs. But as of version 1.0 beta 4, it's not clear you can write Groovy scripts faster than Java. It took me far too long to port Listing 1 to Listing 2, mostly because of inconsistencies in the current implementation, but also because of unimplemented features.

Normally, when I pick up a new scripting language, porting a short program from another language takes very little time. Notice that the Listing 2 example makes fully qualified references to java.awt.Graphics and java.awt.event.ItemEvent.SELECTED despite importing the java.awt and java.awt.event packages and making unqualified references to other Java classes such as Dimension and BorderLayout. The Groovy script would fail to run without making the parameters fully qualified, which is probably a bug that will be fixed. I also discovered the modulo operator was not implemented and neither were bitwise operators such as and, or, and xor.

The one feature I really wanted to test was the extensible Groovy Markup feature. You will notice that the Swing components are implemented with a SwingBuilder class and a unique hierarchical syntax (see Listing 2). The syntax is not native Groovy, but implemented by the SwingBuilder class. HTML and XML builders also have been implemented. I won't describe exactly how it works, but Groovy Markup allows you to express tree-based relationships more succinctly than you would otherwise.

Notice the difference between the assembly of the Swing components in Listing 1 and Listing 2. It looks easier in Groovy doesn't it? Well, looks can be deceiving. The markup makes it difficult to implement listeners that need to manipulate specific objects, such as boardContainer and board (see Listing 1). I had to kluge the listener in Listing 2 to use knowledge of the structure of the assembled frame to access the scroll pane. I would have been better off implementing it the same way as I did in Listing 1, but then what would have been the point of using Groovy?

Scripting languages have a lot to offer Java, and Groovy looks promising. The JSR will be run as an open source project, so Groovy is likely to evolve to meet its user's requirements. You can learn more about Groovy by visiting the project Web site and the JSR 241 Web page (see Resources).

About the Author
Daniel F. Savarese is CTO of Secured Sciences Group, a secure software R&D firm. He has been the founder of ORO Inc., a senior scientist at Caltech's Center for Advanced Computing Research, and vice president of software development at WebOS. Daniel is the original author of the Jakarta ORO text processing packages and the Jakarta Commons Net network protocol library. He is also a coauthor of How to Build a Beowulf (MIT Press, 1999). Contact Daniel at java-pro@fawcette.com.

greenflute 发表于 2006-9-7 10:41

http://www.ftponline.com/javapro/2004_05/magazine/columns/proshop/default_pf.aspx


Resources
       
[*]codehaus: Groovy "Introduction to Groovy"
[*]developer.sun.com The Source for Developers
Java Bug Parade (registration required)
Bug Id 4919127
Bug Id 4960791
[*]Java Community Process Java Specification Requests "JSR 241: The Groovy Programming Language"
[*]"Eclpse vs. Swing" by Daniel F. Savarese (FTPOnline, December 2002)
页: [1]
查看完整版本: [Link]Java Scripting Gets Groovy