Java

Making the Most of Java 5: Annotations

Tagged:  

In this second in a series of articles on the new Java 5 language features, we'll cover annotations. Annotations are used to represent metadata in the Java language, a feature which comes in particularly handy when designing software frameworks, where some type of metadata is often needed to describe the interaction of client software with the container or framework in which it is running. In such a role, they often come into direct competition with the more traditional way of describing metadata with Java, XML.

First, an introduction.

Syntax and Usage

A new symbol is introduced into Java to handle annotations: the '@' character. It is used both in defining and declaring annotations. When defining an annotation, you use a new keyword, @interface. For example,

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
     public String name();
     //Let's assume they are clever...
     public boolean clever() default true;
}

As the keyword implies, annotations are a special type of interface. Here we have defined a new annotation with two properties, 'name' and 'clever'. The 'clever' property has a default value, which is true. This will be supplied if the annotation declaration does not provide a value for this property. The property (or method return types) defined by an annotation are restricted to: primitives, String, Class, annotations, enums, and arrays of these types. Note that there are two basic meta-annotations (annotations on annotations) supplied by Java: @Retention, which specifies at what stages the annotation information is kept, and @Target, which defines on what Java elements an annotation can be used. @Retention takes an enum, RetentionPolicy, that has the values:

CLASS - the annotation is retained in Java .class files but discarded at runtime
SOURCE - the annotation is discarded by the compiler
RUNTIME - the annotation is retained in the Java .class files and kept at runtime

@Target takes an array of an enum, ElementType, which specifies on which Java language elements the annotation can be used. These are:

ANNOTATION_TYPE - an annotation definition
CONSTRUCTOR - a Java type constructor declaration
FIELD - A class-level variable
LOCAL_VARIABLE - A variable declaration local to a block (e.g., a method)
METHOD - A class method
PACKAGE - A package declaration
PARAMETER - A parameter type declared by a Java method
TYPE - a Java class type definition

An annotation can then be used in Java source, like this:

public class MyClass {
     @MyAnnotation(name="Bob")
     public void doSomething() {
          //...
     }
}

Since this is defined as a RUNTIME annotation, it can be reflectively read from the class at runtime. An example might look like this:

public void readAnnotation(Class clazz) {
    MyAnnotation a = clazz.getMethod("doSomething")
          .getAnnotation(MyAnnotation.class);
    System.out.println(a.name() + " is clever? " + a.clever());
}

Vs. XML

Annotations are both very simple and, at the same time, powerful. They have redefined the way that many traditionally XML-based frameworks (EJB 3.0, JAXB, Spring) interact with client code. So what are the advantages or disadvantages of each?

1. XML is more verbose than annotations. Typically, in an XML metadata file, a substantial amount of the structure is dedicated to describing the Java object graph and how the metadata affects it. And verbosity is the natural enemy of readability...
2. XML is less type-safe. It is easy, and common, to mis-type a fully-qualified Java type in an XML file. Most of the time the framework does not check that the type is valid, and will wind up throwing a less-informative error somewhere down the line. Since it is much easier to know the type associated with an annotation (via reflection), this is not a problem. For the same reasons, annotations are much more "tool-friendly".
3. XML files can be more centralized, since they are not co-located with the source. This can be an advantage in certain situations where it is more natural to have the metadata in one place.
4. Annotations are faster. Parsing XML is slower than reflecting annotations, though by how much depends a lot on the situation. If this performance is merely a "startup cost" it may not be relevant at all.
5. Annotations are harder to use with third-party libraries. If you have third-party libraries, and you want to use metadata with those classes, you are out of luck unless the library is open-source. With XML, this is not a problem, because it is not as intrusive.

Some have stated that having annotations on Java source introduces coupling between the source and the metadata. This is not true. Annotations are entirely optional, and need not be read at all. The only potential snag is that having annotations on your source rather than using XML does introduce a stronger dependency on the library (-ies) that contain the annotations, since these must be on your classpath for compilation. But for many, this is not a serious issue.

Conclusion

In general, most framework authors have found that the benefits of annotations outweigh the downsides, and POJOs (Plain Old Java Objects) + Annotations have become the new paradigm in creating Java standards. This is not to say that XML has become obsolete by any means. XML has its place, and always will. But Java developers are certainly relieved by the fact that it is not the only option anymore. And framework writers are relieved that they do not need to parse XML just to get client metadata.

Developing Google Web Toolkit Applications with Netbeans 6

Tagged:  

With the recent release of Netbeans 6 there is a lot of interesting things happening in the Java world. One of the best toolkits for making Ajax applications for Java developers is the Google Web Toolkit. In case you have never used the Google Web Toolkit (a.k.a GWT) it makes it much easier for Java programmers to create Ajax applications as you can code JavaScript in Java. Netbeans 6 now has a GWT plug-in to help you develop your GWT based applications in NetBeans combining the power of these great tools.

Below is an excerpt that will get you started in your development.

Although GWT is not supported in NetBeans 6 out of the box, you can download this GWT plug-in and start developing GWT-based applications in NetBeans.

The first step is to install the plug-in using the Plug-in manager. Go to the "Tools | Plugins" menu action, switch to the "Downloaded" tab and locate the plug-in on your disk drive. You don't even have to restart your IDE - GWT support is instantly available for you!

The plug-in is seamlessly integrated into NetBeans IDE. That means that when you create a new web application GWT is shown as one of the available frameworks in the last step of the New project wizard. Here you can specify the GWT installation folder and choose the main entry point class of your GWT module.

newwebapp.jpg

You can use the plug-in both if you start from scratch or if you want to work on an existing GWT application. So if you used a different IDE than NetBeans before, it is easy to switch the GWT application to NetBeans. You just point the wizard to your existing GWT application and create a new project from existing sources.

Once you get the project created you can run the application simply by hitting the Run button. There are two options – you can either use the default Run action which deploys the application to the application server and opens your default web browser. The other option is to run GWT in hosted mode and then the GWT development shell is opened and you can see your application inside of it.

run.jpg

Debugging is also supported, so you can just run the Debug action and then the runtime is ran in debug mode. You can simply add breakpoints, step into, step out, etc. as you would expect in a regular web application.

debugging.jpg

NetBeans already provides lots of tooling out of the box that you can take advantage of, like a powerful XML editor, HTML editor and of course a Java editor with code completion and quick fixes. NetBeans 6 made huge strides in improving the editing experience and it shows when developing GWT applications, too. All GWT APIs are available for you including javadoc documentation, because the GWT jars get automatically added into the project during it's creation.

To learn more about GWT support in NetBeans, the project homepage and screencast can help you get started. Sang Shin, a member of the Sun technology evangelism team, also created a free course for GWT and NetBeans, so you can learn from his examples and do the hands-on lab.

The plug-in was developed as an open source project so we encourage developers to join the project and contribute. There are many ways you can contribute, even submitting an issue or request for enhancement counts.

The future roadmap contains exciting features such as refactoring for GWT and GWT-specific quick fixes in the editor which will make developing GWT code even more comfortable. We are always looking for feedback, so if you try out the project let the developers know what you think.

Click here to read the full post.

Now that you know about these great tools get to coding some great Ajax applications in Java using the Google Web Toolkit!

Making the Most of Java 5.0: Enum Tricks

Tagged:  

So your organization has finally moved to Java 5.0...and you are wondering what you can do with some of its new features. In this first of a series of articles on Java 5.0, I'll show you some of the interesting ways that you can exploit the new language features to improve the way you code Java.

First off, enumerations.

Introduction to Enums

The enumeration is a way of creating self-documenting code, a big improvement over the "magic" integer or string constants which are often used to represent a defined set of values. Enumerations abound in object models, and examples are not hard to find: days of the week, colors, card suits, etc. The idea of enumerations as an actual programming language type goes back to Pascal. Many programmers, though, are likely to be more familiar with the C/C++ version of it as the enum, which is just a decorated integer:

//use optional assignment to ints to illustrate
enum suit {
   SPADES = 1,
   HEARTS = 2,
   DIAMONDS = 3,
   CLUBS = 4
};

Figure 1: C/C++ enum

Enums in Java

In Java, the introduction of enumerations started informally with Joshua Bloch's type-safe enumeration pattern. The pattern boils down to essentially this: a Java class with a private constructor that declares public static final versions of itself.

public final class Suit {
     private Suit() {}
     public static final Suit SPADES = new Suit();
     public static final Suit HEARTS = new Suit();
     public static final Suit DIAMONDS = new Suit();
     public static final Suit CLUBS = new Suit();
}

Figure 2: The type-safe enumeration pattern

The advantage of this style of enumeration over the C/C++-style enum or constants is that they are "type-safe", meaning that, for example, if you define a method

public void setSuit(Suit suit) { ... }

the caller cannot pass in a value that does not correspond to an enumeration value. With a constant or C/C++-style enum, you could pass in a random value (like -1) that would not. Java-style enumerations have the additional advantage that, since they are classes, you can "associate" other data with them. This idea will be illustrated a little later. Since these enumeration instances are all effectively singletons, they can be compared for equality using identity ("==").

Enums in Java 5.0

In Java 5.0, the enum keyword is introduced as a special type of class that always extends java.lang.Enum. These closely resemble an abbreviated version of Bloch's type-safe enumeration pattern.

public enum Suit {
     SPADES,
     HEARTS,
     DIAMONDS,
     CLUBS        //optionally can end with ";"
}

Figure 3: The Java 5.0 enum

The difference is that this version includes utility methods like name() that returns the declared variable name as a String, ordinal() that returns the position of the enum as it is declared in the class, and valueOf() which allows you to look up the enum using its declared variable name as a String. Java 5.0 enumerations also can be used in switch statements, a nice convenience. Note that the enumeration values are still static class members, though not declared as such.

So, going beyond the basics, what can you do with Java enumerations? Here are a few handy tricks...

Enums and Template Methods

Remember that the enum is basically a special class type, and can have methods and fields just like any other class. Remember also that each declared field is also an instance of the enum. So, applying the "Template Method" design pattern, one can create enumerations that are factories or command objects, but a defined set of objects. Here is a simple example of a "command" enumeration:

public enum Toy {
     DOLL() {
          @Override public void execute() { 
               System.out.println("I'm a doll."); 
          }
     },
     SOLDIER() {
          @Override public void execute() { 
               System.out.println("I'm a soldier."); 
          }
     };
     //template method
     public abstract void execute();
}

Figure 4: The enum with template method

With the use of static imports, the client code calling this enumeration would look like:

SOLDIER.execute();
DOLL.execute();
//or better...
getToy().execute();

The resulting code is clear and self-documenting. Using this pattern is a great alternative in many cases to the more common if(toy=="soldier"){...} else if(toy=="doll"){...} else{...} logic since it is easier to read, extend, and maintain.

Reverse Lookups

Often in your object model it is common to have data that is naturally "associated" with an enumeration. Since an enum is a class, it is easy to represent this associated information as class fields. Often it is desirable to "lookup" the associated enumeration using the field value. This is easy to do using a static java.util.Map. Take, for example, a Status enum that has an associated status code.

public enum Status 
{
     WAITING(0),
     READY(1),
     SKIPPED(-1),
     COMPLETED(5);

     private static final Map<Integer,Status> lookup 
          = new HashMap<Integer,Status>();

     static {
          for(Status s : EnumSet.allOf(Status.class))
               lookup.put(s.getCode(), s);
     }

     private int code;

     private Status(int code) {
          this.code = code;
     }

     public int getCode() { return code; }

     public static Status get(int code) { 
          return lookup.get(code); 
     }
}

Figure 5: The enum reverse lookup

The static get(int) method here provides the reverse lookup by simply getting the value from the Map. The static block to populate the Map uses a specialized implementation of Set, java.util.EnumSet, that "probably" (according to the javadocs) has better performance than java.util.HashSet. Java 5.0 also provides java.util.EnumMap, a specialized implementation of Map for enumerations that is more compact than java.util.HashMap.

Conclusion

The enum in Java 5.0 represents a cleaner, more self-documenting, richer, and in many cases, more efficient way of coding certain object model concepts than was possible using the older idiom of static final constants. Even if you are still using Java 1.4.x or earlier, you can still gain many of the benefits of the enum by using the type-safe enumeration pattern; this will also make the code easier to migrate once you do go to Java 5.0. Older client code that uses constants can still be adapted to use the enum by associating constant values with the enumerations themselves (as seen in the Status class, Figure 5). So, in other words, there is no reason not to convert your old static constants to enumerations. The guy who has to maintain your code will thank you.

Update: there's a second part to this article here.

NetBeans IDE 6.0 Released - Includes Ruby Support

Tagged:  

NetBeans has released version 6.0 of their development IDE. Here's the announcement on their site:

NetBeans.org is proud to announce the availability of NetBeans IDE 6.0! Download now.

The focus of NetBeans IDE 6.0 is superior developer productivity with a smarter, faster editor, and the integration of all NetBeans products into one IDE. NetBeans IDE 6.0 features Ruby/JRuby/Ruby on Rails support, enhancements for improved Swing development, a new Visual Game Designer, updated Data Binding support, integrated Profiling, and more. The new installer lets you customize your download preferences--use it to choose the features and runtimes you need.

The NetBeans IDE is a modular, standards-based, integrated development environment (IDE) written in the Java programming language. The NetBeans project consists of an open source IDE and an application platform, which can be used as a generic framework to build any kind of application.

Among the many new features and enhancements, the IDE now supports Ruby/JRuby/Ruby on Rails.


  • Project Support. Quickly create Ruby projects with logical structure, run Ruby files, configure other Ruby interpreters (such as JRuby or native Ruby), locate and install Ruby Gems through a graphical wizard, create and execute unit tests, run RSpec specification files, jump between a Ruby file and its corresponding unit test or spec file, and so on. View Demo.
  • Advanced Ruby Editing. Advanced code editing for Ruby, using semantic information about the program to offer code completion, showing available classes and methods for the current expression, along with the associated RDoc documentation. The syntax highlighting is enhanced with semantic information, such that unused local variables and parameters are shown in gray. There are many other editing features, including Goto Declaration for jumping to the declaration point of a class or method reference. View Demo.
  • Ruby Debugger. Single-step or run through Ruby code, set breakpoints, look at local variables, navigate the call stack, switch threads, and evaluate expressions by just hovering the mouse over the variable in the Editor. There is also support for the "fast debug" extension.
  • Ruby on Rails Support. Generate Rails projects, or generate code through the Rails code generator graphical wizard, which offers documentation on the plugins within the wizard itself. Third party generators are also supported. Furthermore, there are actions for jumping quickly between a Rails action and its corresponding View, or warping to the browser for the URL most relevant to the file you are editing. Database migrations and Rake targets are supported as well. Finally, RHTML files are highlighted (along with improved NetBeans 6.0 support for related files, such as JavaScript and CSS). View Demo.

Other features include:

  • Editor Improvements
  • Easier Installation and Upgrading
  • Swing GUI Development
  • Profiling
  • Web and Java EE
  • Mobility
  • SOA
  • UML
  • C/C++
  • NetBeans Platform API Improvements



Click here to read more about these features or to download the new IDE.


Optimize your Ajax with TIBCO General Interface Performance Profiler

Tagged:  

TIBCO General Interface Performance Profiler

As the complexity of your Ajax applications increase, so do the opportunities for performance issues to arise. Checkout TIBCO General Interface Performance Profiler, an open source (BSD License) Ajax application profiling tool for benchmarking the performance of Ajax solutions created with TIBCO General Interface and other Ajax toolkits. Create performance testing scripts in JavaScript then run them against live applications to get performance statistics for selected operations within your application. The Performance Profiler is smart enough to let you handle asynchronous operations too.

With this profiler, you can now dissect your application to test how long it takes your services to respond, your components to render, your data to parse, and your functions to execute. Basically everything you need to pinpoint the bottlenecks in your code. One thing this profiler won't do -- optimize your code for you -- that's your job.

Click here to vist Tibco's GI Performance Profiler Homepage

JavaFX: The Second Coming of Swing

Tagged:  

At JavaOne 2007, Sun announced with much fanfare its JavaFX platform including two major components: Mobile and Scripting. This article will focus on the most interesting aspect of this new platform (for Swing old-timers, at least), the Java FX Script component. For interested parties, all of the relevant files can be found in the OpenJFX project hosted on java.net. The distribution is currently just a dump of the Subversion tree, but contains plenty of goodies to get started with the language. For those who are merely interested in sampling what Java FX can do, there are plenty of JNLP-based demos which can be launched from the main page (a 1.5+ JRE is required to be installed on the client).

The First Coming of Swing

Some of us may remember the first time Sun introduced AWT (later to evolve into Swing) to an excited world in 1995. It wasn't long before many developers were eagerly creating Applets in their web browsers, marvelling at the prospect of code being streamed over the network and executed in their browser. Applets were cool. Applets were hot. Applets were...well, ugly. Back then, though, Windows 95 defined computer aesthetics, and Applets didn't suffer too much in comparison.

Fast forward several years, and the picture has changed rapidly. Swing is no longer the disruptive technology that it once seemed to be. After Microsoft began neglecting its Java implementation for Windows/IE (coincidentally after a long battle with Sun over its embrace-and-extend tactics) and Netscape lost the browser wars, Swing had become less important as a technology. Most web developers moved on to using Flash, Java moved into its server-side stronghold (having failed to really take off on the desktop), and Swing was left to stagnate. Swing continued to improve over the years, but Sun's--and most of the world's--attention had moved elsewhere.

Enter JavaFX

In 2005 Sun acquired SeeBeyond Technology Corporation, an employee by the name of Chris Oliver, and a little creation of his called F3 (Form Follows Function), later dubbed JavaFX Script. Sun saw its opportunity to position itself in the Rich Internet Application (RIA) market, and set its sights on competitors, Microsoft's Silverlight and Adobe's AIR (Flex). It's too early to tell what the success of JavaFX Script will be, but Swing has come a long way since the heady early days of the Internet and JavaFX may be just the trick in smoothing some of the pain points in developing with Swing.

Introduction to JavaFX Script

To veteran Java developers, JavaFX Script will seem both familiar and strange at the same time. Depending on which style of the language you develop in, it can look either like JavaScript or like "CSS with scripting". What follows is an example, written in both styles, with the obligatory "Hello World":

Frame {
title: "Hello World Frame"
width: 250
content: Label {
text: "Hello World"
}
visible: true
}

Figure 1a: Hello World in "CSS with Scripting" style

Or

var f = new Frame();
f.title = "Hello World Frame";
f.width = 250;
var label = new Label();
label.text = "Hello World";
f.content = label;
f.visible = true;

Figure 1b: Hello World in JavaScript style

Run either of these examples in the JavaFXPad application (provided in the distribution or via JNLP on the web site), and you will see the familiar Swing frame with its content as a single label containing the text "Hello World". It isn't hard to see that JavaFX is much more compact than the equivalent Java code. That in itself addresses one of the major difficulties in developing in Swing, but JavaFX Script is more than that. The language contains "shortcuts" that make more sophisticated development in Java 2D and 3D as easy as doing it in a declarative language such as SVG or Flex. The default code displayed when JavaFXPad launches demonstrates this convincingly, showing how easy it is to do scaling, transforms, or create a shadow filter.

Core Language

JavaFX Script contains a lot of syntactic similarities to both Java and JavaScript, so many constructs will already be familiar to an experienced developer. This section will highlight some of the important differences and unique features of JFX Script.

Primitives Values

JFX Script has four primitives: String, Boolean, Number, and Integer (all whole number values, i.e., byte, int, long, etc.).

Operators

JFX Script replaces the more C++-like !, &&, and || with not, and, and or.

For Loops

JFX Script has a version of the "foreach" constructs that allows iteration over an interval, like so

for(i in [0..5]) {
//do something
}

Operations and Functions

JFX Script has two different keywords to declare methods: operation and function. Funcions in JFX Script are forbidden to have loops or conditional operands in order to minimize potential side-effects. Why is this needed? Because a function re-evaluates its return value every time one of its input parameters or referenced variables is changed. This turns out to be very handy when you want to bind some output to values that frequently change. Operations are more like normal Java methods.

IDE Support

Obviously, the JavaFXPad application is insufficient for real-world development, so early versions of plugins for using JFX Script with Netbeans and Eclipse are available. Of the two, the Netbeans plugin seems further along in its development (it is a Sun technology, of course ;) ), but expect this to change as the project nears release. See the OpenJFX site for downloads and instructions.

Conclusion

JavaFX Script is still very much in pre-release stage, but is already looking like an extremely promising technology. Currently, it runs in interpreted mode but a compiler is being developed for the language that will compile scripts straight into Java bytecode, giving the same performance as the equivalent Swing code with a fraction of the effort. It definitely has an uphill battle in the race for the RIA market, but for existing developers that use Swing it is already a winner.

Syndicate content