explore the new features of eclipse v3 · features shown here are tailored to j2se v1.5, it's...

30
Explore the new features of Eclipse V3.1 Better usability, more expansive Java support, and enhanced performance improve the Eclipse integrated development environment Skill Level: Intermediate Martin Streicher ([email protected]) Editor-in-Chief Linux Magazine 21 Feb 2006 This tutorial demonstrates many of the new features found in the most recent release of Eclipse: V3.1. You will find this tutorial useful if you're considering upgrading to V3.1 from a previous release, or if you're considering switching to Eclipse from another integrated development environment. You may also find it useful if you want to revise your code to take advantage of the latest iteration of the Java™ language, Java 2 Standard Edition V1.5, which adds a number of powerful constructs and conveniences to Java technology. Section 1. Before you start Learn what to expect from this tutorial and how to get the most out of it. About this tutorial This tutorial demonstrates many of the new features found in the most recent release of the Eclipse platform, V3.1. You will find this tutorial useful if you're considering upgrading to V3.1 from a previous version, or if you're considering switching to Eclipse from another integrated development environment (IDE). You may also find it useful if you want to revise your Java code to take advantage of the Explore the new features of Eclipse V3.1 © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 30

Upload: others

Post on 20-Jun-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Explore the new features of Eclipse V3.1Better usability, more expansive Java support, and enhancedperformance improve the Eclipse integrated developmentenvironment

Skill Level: Intermediate

Martin Streicher ([email protected])Editor-in-ChiefLinux Magazine

21 Feb 2006

This tutorial demonstrates many of the new features found in the most recent releaseof Eclipse: V3.1. You will find this tutorial useful if you're considering upgrading to V3.1from a previous release, or if you're considering switching to Eclipse from anotherintegrated development environment. You may also find it useful if you want to reviseyour code to take advantage of the latest iteration of the Java™ language, Java 2Standard Edition V1.5, which adds a number of powerful constructs and conveniencesto Java technology.

Section 1. Before you start

Learn what to expect from this tutorial and how to get the most out of it.

About this tutorial

This tutorial demonstrates many of the new features found in the most recentrelease of the Eclipse platform, V3.1. You will find this tutorial useful if you'reconsidering upgrading to V3.1 from a previous version, or if you're consideringswitching to Eclipse from another integrated development environment (IDE). Youmay also find it useful if you want to revise your Java code to take advantage of the

Explore the new features of Eclipse V3.1© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 30

latest iteration of Java: Java 2 Standard Edition (J2SE) V1.5, which adds a numberof powerful constructs and programming conveniences to the core Java language.

Objectives

In this tutorial, you discover many of the new features of Eclipse V3.1. You learnhow to install the Eclipse platform and the underlying Java Virtual Machine (JVM)software, examine many Eclipse V3.1 innovations, and explore numerous examplesof how the new Java Development Tools (JDT) hasten development with the newlanguage constructs of J2SE V1.5.

Prerequisites

To benefit from this tutorial, you should have experience with Java softwaredevelopment and some experience creating code in an IDE. You should also haveexperience installing software from the command line, and setting and managingshell and system environment variables, such as the Java language's CLASSPATHand the system's PATH. Acquaintance with previous releases of Eclipse is alsobeneficial, but isn't required.

Before you start, you must install several software packages on your UNIX®,Solaris, Linux®, Mac OS X, or Microsoft® Windows® system.

Specifically, you need a functioning JVM and a copy of the Eclipse V3.1 platform.Here's the complete list of software that you need:

• The J2SE V1.5 Software Development Kit (SDK) (J2SE V1.5 is alsoreferred to as Java 2 Platform, Standard Edition V5.0.)

• The J2SE V1.5 Java Runtime Environment (J2RE)

• The Eclipse V3.1 SDK

System requirements

Any computer with a JVM should be able to run Eclipse. However, since many of thefeatures shown here are tailored to J2SE V1.5, it's best if your machine can run thatversion of Java. Sun Microsystems provides versions of J2SE V1.5 for Solaris,Windows, and Linux. Apple provides J2SE V1.5 for Mac OS X (as of version 10.4.4).Other platforms may also be supported. See Resources for links to the J2SE V1.5software.

developerWorks® ibm.com/developerWorks

Explore the new features of Eclipse V3.1Page 2 of 30 © Copyright IBM Corporation 1994, 2008. All rights reserved.

If you do not have J2SE V1.5 and Eclipse V3.1 installed, make sure you have atleast 300 MB of physical disk space free before proceeding. You should also haveenough RAM to run the JVM. In general, 64 MB or more of free physical memory isrequired to run the JVM. A large amount of free RAM typically translates to betterperformance.

Section 2. Introducing Eclipse

In a relatively short time, Eclipse has become a popular foundation for thedevelopment of other IDEs and a wide variety of applications in many problemdomains.

For instance, the Ruby Development Tool (RDT) (see Resources) is a set ofRuby-specific plug-ins that turn Eclipse into a powerful Ruby editor. Meanwhile,Azureus, a highly regarded and widely used Java application that downloadsBitTorrent torrents (large collections of files), is based on Eclipse's Rich ClientPlatform (RCP).

Of course, Eclipse is also an increasingly capable and favored IDE for coding manyprogramming languages. Given its extensible framework, developers often tailorcutting-edge development tools solely for Eclipse. Given its popularity, commercialdevelopment tools vendors such as Rational® and Oracle now ship productsdesigned specifically to integrate into Eclipse.

In addition, the governing body of Eclipse, the Eclipse Foundation, continuouslyfunds core projects to further expand the capabilities of Eclipse. For instance, theEclipse Test and Performance Tools Platform (TPTP) project has added test,performance benchmarking, and monitoring tools to the core Eclipse platform.Another project, the Eclipse Web Tools Platform (WTP) project, continues to addtools and technology to assist the development of Web-centric applications.

All in all, Eclipse is both a platform and an umbrella for a great number of tools thathasten development, ease re-development (or refactor), simplify porting to multipleplatforms (via packages like the Standard Widget Toolkit (SWT)), and manage theentire software development life cycle -- from the first line of code to productionsystem monitoring.

Eclipse V3.1

ibm.com/developerWorks developerWorks®

Explore the new features of Eclipse V3.1© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 3 of 30

In June 2005, after a full year of development, the Eclipse Foundation released asignificant new version of Eclipse: V3.1. Improvements in the new release span fromthe core Eclipse platform to the Eclipse JDT and the Eclipse Plug-in DevelopmentEnvironment (PDE), a complete environment for developing software that extendsEclipse. If you haven't tried Eclipse for a while or have yet to use Eclipse, V3.1deserves a close look.

New features, both large and small, in Eclipse V3.1 include:

Better performancePrior to V3.1, Eclipse had a reputation for being sluggish. To address theconcerns of many developers, considerable time and effort was spent tooptimize the platform, with impressive results. In V3.1, Eclipse's memoryfootprint is smaller, and the entire Eclipse platform is faster and moreresponsive across all platforms (including Mac OS X, Windows, and Linux).Moreover, the platform has been instrumented thoroughly, making performancedegradations (and improvements) quite visible.For example, the graph in Figure 1 shows some benchmark results for EclipseV3.1.1, the most recent maintenance release (see Resources for the inventoryof bugs fixed in V3.1.1.).

Figure 1. A portion of performance benchmarks for Eclipse V3.1.1

Similar graphs exist for subsequent releases of Eclipse, even for nightly builds of thesoftware. You can find more benchmark results on the Eclipse Web site.

Smarter HelpEclipse V3.1 includes a new context-sensitive dynamic Help system that keepspace with you as you change from task to task. Move from one view to another-- even from one line of code to the next -- and the dynamic Help view updates

developerWorks® ibm.com/developerWorks

Explore the new features of Eclipse V3.1Page 4 of 30 © Copyright IBM Corporation 1994, 2008. All rights reserved.

to present the most relevant list of topics and documentation for the task athand.

Improved usabilityMajor and minor changes make the Eclipse platform simpler to use. Forexample, the entire platform now supports bi-directional languages, you canuse a keyword to filter preferences or properties -- no more frantic browsingthrough long lists (Figure 2 shows the preferences that match the keywordtab), you can import multiple projects at a time and can even import from a taror zip archive, plug-in installation is as simple as installing a single jar file, andthe new Install Wizard installs all plug-in dependencies automatically.

Figure 2. Searching for all preferences panels that affect tabs

ibm.com/developerWorks developerWorks®

Explore the new features of Eclipse V3.1© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 5 of 30

J2SE V1.5

In addition to the many niceties listed above, all the new Java languageenhancements found in J2SE V1.5 are supported in Eclipse V3.1, includinggenerics, auto-boxing, enhanced for loops, annotations, and enumerated types(enums), among others. J2SE V1.5 not only expands the Java language but many ofits features make the programming language more type-safe, leading to morecompile-time errors and fewer runtime errors.

developerWorks® ibm.com/developerWorks

Explore the new features of Eclipse V3.1Page 6 of 30 © Copyright IBM Corporation 1994, 2008. All rights reserved.

For example, Listing 1 demonstrates a handful of new J2SE V1.5 features:

Listing 1. New J2SE V1.5 features

package demo;

import java.util.ArrayList;

public class Shapes {

public enum Shape {SQUARE (2),CIRCLE (1),TRIANGLE (3);

private final Integer data;

Shape(int i) {this.data = i;

}

public int value() {return this.data;

}}

public static void main(String[] args) {ArrayList<Shape> a = new ArrayList<Shape>();for (Shape s: Shape.values()) {

a.add(s);}

for (int i = 0; i < a.size(); i++) {Shape s = a.get(i);double perimeter = 0;

switch (s) {case SQUARE:perimeter = s.value() * 4;break;

case CIRCLE:perimeter = s.value() * 3.14159;break;

case TRIANGLE:perimeter = s.value() * 3;break;

}

System.out.print("The perimeter of a " +s.value() + "-inch + s + " is " +perimeter + " inches" );

}}

}

Quickly, J2SE V1.5's new enumerated types are full-fledged classes that can havemethods, properties, and more. Auto-boxing and auto-unboxing provide quickpromotion from a primitive type to a compatible class and vice-versa, respectively.Hence, this.data = i requires no promotion (found in code such as this.data

ibm.com/developerWorks developerWorks®

Explore the new features of Eclipse V3.1© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 7 of 30

= new Integer(i)).

Generic collections such as ArrayList can now accept a type parameter such asShape that restricts the members of that collection to the specified type. Moreover,the type returned by the collection is also fixed. Hence, a statement such asa.get(i) no longer must be "demoted" or cast from Object to Shape. This latterset of features is collectively called generics.

Finally, the code for (Shape s: Shape.values()) is new shorthand for iteratingover members of a list.

This section presented just a short list (for brevity's sake) of the many improvementsfound in Eclipse V3.1. Many of the improvements listed above -- and others -- aredemonstrated throughout the balance of this tutorial.

Section 3. Installing the prerequisite software andcomponents

Before you can begin this tutorial, you must install and set up the software andcomponents listed in Prerequisites.

Install J2SE V1.5 and J2RE V1.5

Download and install the J2SE V1.5 SDK and the V1.5 J2RE. (If your systemalready has J2SE V1.5.0_06 or a later version, you can skip this.)

Typically, the J2SE SDK and JRE are distributed as self-extracting binaries.Installation (on Linux) is typically as easy as this (assuming that you downloaded theJ2SE and J2RE packages to your home directory):

% cd ~% mkdir ~/java% cd ~/java% mv ~/jdk-1_5_0_06-linux-i586.bin .% mv ~/jre-1_5_0_06-linux-i586.bin .% chmod +x jdk-1_5_0_06-linux-i586.bin \

jre-1_5_0_06-linux-i586.bin% ./jdk-1_5_0_06-linux-i586.bin..% ./jre-1_5_0_06-linux-i586.bin..

developerWorks® ibm.com/developerWorks

Explore the new features of Eclipse V3.1Page 8 of 30 © Copyright IBM Corporation 1994, 2008. All rights reserved.

% ls -Fjdk1.5.0_06/ jre1.5.0_06/

Install the Eclipse V3.1 SDK

Download the Eclipse V3.1 SDK appropriate for your platform. You can find the SDKat the Eclipse Downloads. Typically, installation is as easy as unpacking the Eclipse.tar.gz file into the directory of your choice. For example, if you're using Linux,download the Eclipse V3.1 SDK tarball, and then unpack it in a directory such as~/java/ using these commands:

% cd ~/java% mv ~/eclipse-SDK-3.1.1-linux-gtk.tar.gz .% tar zxvf eclipse-SDK-3.1.1-linux-gtk.tar.gz

To verify that Eclipse was installed successfully, remain in the directory where youunpacked Eclipse, make sure that the java executable is in your PATH, and runjava -jar eclipse/startup.jar. For example:

% export JAVA_DIR=$HOME/java% export JAVA_HOME=$JAVA_DIR/jdk1.5.0_06/sdk% export PATH=$JAVA_HOME/bin% export CLASSPATH=$JAVA_HOME% cd $JAVA_DIR% java -jar eclipse/startup.jar

If Eclipse prompts you to choose a directory for your workspace, type$HOME/java/workspace. This directory retains all the projects you create inEclipse. (Of course, if you have many projects, you can create other workspaceslater, perhaps to contain one project per workspace.)

Section 4. Programming with generics

One of the most significant additions to Java in J2SE V1.5 is generics. To appreciatethe value and purpose of generics, take a look at Listing 2.

Listing 2. Inserting and extracting an element from a hash table

ibm.com/developerWorks developerWorks®

Explore the new features of Eclipse V3.1© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 9 of 30

import java.util.Hashtable;class Demo{

public static void main(String[] args){Hashtable h = new Hashtable();

h.put(new Integer(0), "HorseFeathers");

String s = (String) h.get(newInteger(0));

System.out.println(s);}

}

Code like that is laborious to write over and over again, as you'll surely attest, andthe complexity of the highlighted line of code belies its otherwise simple purpose.Worse, mismatched types -- say, casting to the wrong type after retrieving the objectwith h.get() -- cannot be caught by the compiler. Indeed, downcasting (theprocess of casting "down" the object inheritance tree, from an Object to a String,say) is a huge source of runtime bugs in Java programs.

Of course, an alternative is to implement your own hash table using fixed types. Forinstance, perhaps MyStringHashTable might wrap the generic Hashtable andadd only String elements with Integer indices. In that case,MyStringHashTable.put() and MyStringHashTable.get() would be(re)defined appropriately to accept only properly typed parameters and return aString, respectively.

While such a MyStringHashTable is type-safe, it's no longer flexible. To store anew form of data in a hash, you have to recreate much of the MyStringHashTablecode in an entirely new and separate object.

Enter generics

Ideally, something like a Hashtable class would be flexible and rigid (type-safe):The types of the keys and the values would be parameterized at instantiation, forinstance, obviating the need for casts and allowing the compiler to catch typemismatches. And, indeed, parameterized types are the foundation that underliesJava V1.5's new generics.

Creating and using generics

In this section, you use Eclipse and its support of generics to create and refine asample application.

developerWorks® ibm.com/developerWorks

Explore the new features of Eclipse V3.1Page 10 of 30 © Copyright IBM Corporation 1994, 2008. All rights reserved.

1. If you haven't started Eclipse yet, launch it, go to the Workbench, andcreate a new project. To do the latter, select File > New > Project....Specify Generics Example as the project name and choose 5.0 fromthe JDK Compliance section (click the drop-down menu to find it). Finally,click Finish.

2. Create a Java class in your new project. Select File > New > Class, typedemo for the package name, and enter Demo as the name. Select thecheck box that generates a public static void main(String[]args) method stub. Now, click Finish.

3. Click on the new Demo class in the Package Explorer pane, then copyand paste the code from Listing 3 into the Demo.java pane.Listing 3. A simple generic class

package demo;

class GenericContainer <A>{

private A data;

public GenericContainer(A data){this.data = data;

}

public A get(){return data;

}}

public class Demo{

public String storeString(String s){GenericContainer<String> gc =

new GenericContainer<String>(s);String t = gc.get();return t;

}

public Integer storeInteger(Integer i){GenericContainer <Integer> gc =

new GenericContainer<Integer> (new Integer(i));return gc.get();

}

public static void main(String[] args) {Demo d = new Demo();

System.out.println(d.storeString("This is a test"));System.out.println(d.storeInteger(18000));

}}

ibm.com/developerWorks developerWorks®

Explore the new features of Eclipse V3.1© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 11 of 30

4. Use Ctrl+S to save the code and select Run > Run.... When the Rundialog opens, click the Run button at the bottom right. The output paneshould produce the following:

This is a test18000

5. Hover slowly over each call to gc.get(). If you hover over the firstusage in storeString, a little note pops up to indicate that gc.get()returns a String, while hovering over the second use indicates that theinstance method returns an Integer (see Figure 3).

Figure 3. Hover over a generic method call to see the type it returns

Now that you know why generics were added to Java and how generics work, I'llshow you how generics are supported and reinforced in Eclipse V3.1.

Catching errors with generics

Since generics are intended to help avoid downcasting errors, Eclipse flags thoseoperations where the use of a generic would be beneficial.

For example, create the following short Java application in Eclipse using the 5.0compiler setting:

package demo;

developerWorks® ibm.com/developerWorks

Explore the new features of Eclipse V3.1Page 12 of 30 © Copyright IBM Corporation 1994, 2008. All rights reserved.

import java.util.ArrayList;

public class Demo2 {

public static void main(String[] args) {ArrayList a = new ArrayList();a.add(new Integer(1));

}}

After you enter the code, two small icons -- a light bulb and a warning sign -- shouldappear on the line that begins a.add(...), as shown in Figure 4. If you hover overthe icon, a message alerts you that the use of ArrayList should be parameterized.

Figure 4. Eclipse points out when generics are preferable

The more type-safe code is ArrayList>Integer< a = newArrayList>Integer<().

Eclipse also offers refactoring techniques that promote the use of generics. Look atListing 4.

Listing 4. Code to be refactored to use generics

package demo;

import java.util.ArrayList;import java.util.List;

public class Demo3 {public class Brother {

private String name;

public Brother(String s) {name = s;

}

public String get() {return name;

}}

public static void main(String[] args) {Demo3 d = new Demo3();

List l = new ArrayList(3);l.add(d.new Brother("Groucho"));l.add(d.new Brother("Harpo"));l.add(d.new Brother("Chico"));l.add((Brother) l.get(1));

for (int i = 0; i < l.size(); i++) {Brother b = (Brother) l.get(i);System.out.println(b.get());

}

ibm.com/developerWorks developerWorks®

Explore the new features of Eclipse V3.1© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 13 of 30

}}

After you enter the code above, Eclipse should flag a number of lines with a lightbulband wavy yellow lines, indicating that improvements can be made. To refactor to usegenerics, select Refactor > Infer Generic Type Arguments. When the next dialogappears, leave both options enabled, then click the Preview button. Eclipse exhibitsthe proposed changes, as shown in Figure 5.

Figure 5. Eclipse previews the refactoring to generics

Not only did Eclipse refactor to parameterize both List and ArrayList but it alsoremoved the cast in the for loop. Click OK to accept the changes. The code istransformed to this:

List>Brother< l = new ArrayList>Brother<(3);...l.add(l.get(1));

developerWorks® ibm.com/developerWorks

Explore the new features of Eclipse V3.1Page 14 of 30 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Finally, anywhere that Eclipse handles a nongeneric type, it can handle a generictype. You can safely rename generic types, for example.

A new loop

Along with the addition of generics, Java V5 now supports a shorthand foreach toiterate over the elements of a list. The decidedly old-fashioned for loop that printsthe members of List l can be rewritten more succinctly as this:

for (Brother b: l)System.out.println(b.get());

As for many older Java language features, Eclipse V3.1 includes a template for thenew J2SE V1.5 foreach construct. Eclipse not only produces the foreach codefor you but it also guesses (from context and location) which collection you want toiterate over.

For example, type fore after the last l.add(), then press Ctrl+Space. Eclipsepresents the foreach template as an option and shows you the code it wouldgenerate, as shown in Figure 6.

Figure 6. Eclipse can automatically generate foreach loops based on context

Choosing the suggested foreach template produces this:

ibm.com/developerWorks developerWorks®

Explore the new features of Eclipse V3.1© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 15 of 30

for (Brother brother : l) {

}

Section 5. More J2SE V1.5 language features

While the addition of generics is sure to reduce the number of bugs in your Javacode, other J2SE V1.5 features are sure to make you more productive.

J2SE V1.5 introduced a number of language features that simplify development. Inthis tutorial, you look at two of them: auto-boxing and enumerated types.

Auto-boxing

Auto-boxing and auto-unboxing provide a simple, clean syntax for assigningprimitive values to objects and for reading primitive values from objects. Forexample, in the past you wrote this:

public class Box {public Box(Integer i) {...}

}

...

Box o = new Box(new Integer(1));

You can now write Box n = new Box(2), instead. Better yet, Eclipse V3.1 canhighlight instances of auto-boxing and auto-unboxing.

To see the feature, cut and paste Listing 5 into a new class in Eclipse.

Listing 5. Demonstration of auto-boxing and auto-unboxing

package demo;

public class Box {

private Integer data;

public Box(Integer i) {

developerWorks® ibm.com/developerWorks

Explore the new features of Eclipse V3.1Page 16 of 30 © Copyright IBM Corporation 1994, 2008. All rights reserved.

data = i;}

public Integer get() {return data;

}

public static void main(String[] args) {Box o = new Box(new Integer(100));Box n = new Box(200);int oi = o.get().intValue();int ni = n.get();System.out.println("Your numbers are " + oi

+ " and " + ni);}

}

Select Windows > Preferences..., then Java > Editor > Syntax Coloring > Java >Auto(un)boxed Expressions to reveal the options shown in Figure 7. SelectEnable, then select Bold, then click Apply and OK.

Figure 7. Highlighting instances of boxing and unboxing

When you return to your class pane in Eclipse, the instance of boxing, newBox(200), and unboxing, ni = n.get(), are red and bold, per yourspecifications:

Figure 8. Highlighting instances of boxing and unboxing

ibm.com/developerWorks developerWorks®

Explore the new features of Eclipse V3.1© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 17 of 30

If you'd like the compiler to additionally flag instances of auto-boxing andauto-unboxing, go to Window > Preferences, then Java > Compiler >Errors/Warnings > J2SE 5.0 Options, then set Boxing and unboxingconversions to either Warning or Error.

And remember, you can find any preference setting quickly by typing a keyword intothe search box in the Preferences dialog. For instance, select Window >Preferences, then type boxing in the search box. The panels with relevant optionsappear, as shown in Figure 9.

Figure 9. Finding the preferences that affect auto-boxing and auto-unboxing

developerWorks® ibm.com/developerWorks

Explore the new features of Eclipse V3.1Page 18 of 30 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Enumerated types

In prior releases of the Java language, enumerated types were typicallyimplemented manually:

public static final int GROUCHO_MARX = 0;public static final int HARPO_MARX = 1;public static final int CHICO_MARX = 2;public static final int KARL_MARX = 3;

Positively old-fashioned, such artificial enumerated types aren't type-safe, lack anamespace, and are brittle, meaning that changing the constants can wreak havocbecause the values are compiled into one or more modules or programs. If you failto recompile and reinstall every module that references the constants, the behavior

ibm.com/developerWorks developerWorks®

Explore the new features of Eclipse V3.1© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 19 of 30

of the system is unpredictable at best.

To remedy the many faults of program-your-own enums, J2SE V1.5 added afull-fledged class called an enum type to represent enumerated types.

In simplest form, J2SE V1.5's enumerated types look a lot like the similar constructin other programming languages. For example, here is the modern Java equivalentof the code shown above:

public enum Actors {GROUCHO, CHICO, HARPO, KARL

}

And here is some code to iterate through the list of all values:

package demo;

public class Demo4 {public enum Actors {GROUCHO, CHICO, HARPO, KARL

}

public static void main(String[] args) {for (Actors actor : Actors.values())

System.out.println("Say hello to " + actor);}

}

Since enums are now classes in the Java language, Eclipse provides a separatedialog to create them. Select File > New > Enum to open the dialog box shown inFigure 10.

Figure 10. Creating a new Java enum with Eclipse

developerWorks® ibm.com/developerWorks

Explore the new features of Eclipse V3.1Page 20 of 30 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Java enums can also be compared and are serializable. Furthermore, enums canhave methods and properties just like other objects. So, the previous Actors couldbe further extended to the following:

package demo;

public class Demo4 {public enum Actors {GROUCHO ("What about this sanity clause?"),CHICO ("Everyone knows there ain't no such " +

"thing as sanity clause!"),KARL ("Ugh!"),HARPO ("Honk! Honk!");

private final String line;

Actors(String s) {this.line = s;

}

ibm.com/developerWorks developerWorks®

Explore the new features of Eclipse V3.1© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 21 of 30

public String line() {return line;}}

public static void main(String[] args) {for (Actors actor : Actors.values())

System.out.println(actor.line());}

}

If you copy and paste that code into a new Eclipse class called Demo4 and run thecode, you should see this:

What about this sanity clause?Everyone knows there ain't no such thing as sanity clause!Ugh!Honk! Honk!

And if you have the Outline view open, Eclipse provides a skeletal view of the newenum, as shown in Figure 11.

Figure 11. An outline of a new Java enum type class

developerWorks® ibm.com/developerWorks

Explore the new features of Eclipse V3.1Page 22 of 30 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Section 6. Additional novelties

Beyond improving the speed and accuracy of your programming, Eclipse V3.1 adds

ibm.com/developerWorks developerWorks®

Explore the new features of Eclipse V3.1© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 23 of 30

a number of features to assist you as you navigate the Eclipse interface itself.You've seen some already: You can search the numerous Eclipse preferencespanels to find attributes by keyword, and you can highlight many languageconstructs in the editor to make your code more readable.

There are some other conveniences you may find helpful.

Key bindings

In any Eclipse editor or view, use Ctrl+Shift+L to see a complete list of available keybindings. For example, in the Java editor, Ctrl+Shift+L produces a long list offeatures you can use straight from your keyboard (see Figure 12).

Figure 12. Show all key bindings by pressing Ctrl+Shift+L

developerWorks® ibm.com/developerWorks

Explore the new features of Eclipse V3.1Page 24 of 30 © Copyright IBM Corporation 1994, 2008. All rights reserved.

You can also find a list of key bindings in the General > Keys preference page. (Youcan open that page directly by using Ctrl+Shift+L again in the key bindingslisting, as the hint at the bottom of Figure 12 suggests.)

Dynamic Help

Since Eclipse incorporates so many tools so fluidly, you can easily change fromeditor to profiler to project editor with just a few clicks of the mouse. The Helpsystem in Eclipse V3.1 has been improved to keep pace with the way you work.

If you press F1 or select Help > Dynamic Help from the menu, Eclipse presents acontext-sensitive Help panel that dynamically changes as you move from task totask. A sample Help view is shown in Figure 13.

Figure 13. The Eclipse dynamic Help system

ibm.com/developerWorks developerWorks®

Explore the new features of Eclipse V3.1© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 25 of 30

developerWorks® ibm.com/developerWorks

Explore the new features of Eclipse V3.1Page 26 of 30 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Open one of your Java files or one of the examples in this tutorial and click ondifferent lines. The Help view should change to reflect the context. Keep the Helpview open as you move through some of the next sections.

Annotations

J2SE V1.5's annotations allow you to attach metadata about Java types andmethods to your source code. The annotations can then affect the compilationprocess (and can even be queried at runtime).

If you didn't enable compiler warnings for auto-boxing and auto-unboxing, go aheadand do that now, and reopen the auto-boxing sample code, if necessary. Oncewarnings are enabled, the instance of auto-boxing and auto-unboxing should beflagged.

Click on the first warning icon. You should receive two choices: one to extract theconstant 200 to a local variable and another to add a @SuppressWarnings'boxing' annotation to main(). Choose the latter. Your code is transformed tothis:

@SuppressWarnings("boxing")public static void main(String[] args) {...}

Now, if you rebuild the auto-boxing example, Eclipse won't generate any warningsand the warning icons that were displayed previously are removed.

Like other language constructs, Eclipse V3.1 can automatically expand availableannotations. For example, in the auto-boxing example, place your cursor next to theget() method and type @D, followed by Ctrl+Space. In the list of options, choosethe annotation @Deprecated, which indicates that this method has beendeprecated (say, if you wrote a better get() method or if get() was no longersupported).

Depending on your preferences, the name of the get() method will be struck whereit is defined and in the two lines that call the method (see Figure 14).

Figure 14. Annotating a method to indicate that its use has been deprecated

ibm.com/developerWorks developerWorks®

Explore the new features of Eclipse V3.1© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 27 of 30

If you still have the Help view open and you click on the @Deprecated annotation,the top-most entry points to the Javadoc for java.lang.Deprecated.

Section 7. Summary

Whether you develop tools, applications, or lots and lots of Java code, Eclipse V3.1is sure to make you more productive. It runs on all the most popular operatingsystems -- and runs faster -- and continues to amass an enormous set of features.

Indeed, if you're a Java developer, Eclipse's Java Development Tools and its Testand Performance Tools Platform provide a comprehensive suite of tools to create,debug, tune, and monitor your applications. The Java 2 Standard Edition V1.5makes Java more type-safe and simpler to use, and Eclipse V3.1 supports andreinforces all of the J2SE V1.5 key constructs.

As you can see just from the few examples presented here, programming Java inEclipse is simply a joy.

developerWorks® ibm.com/developerWorks

Explore the new features of Eclipse V3.1Page 28 of 30 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Resources

Learn

• Learn more about the Eclipse Foundation and its many projects.

• Read "Introduction: Eclipse Test and Performance Tools Platform" forbackground information about TPTP.

• "An Introduction to the Eclipse Web Tools Platform V1.0" provides backgroundinformation about WTP.

• "Diagnosing Java Code: Java Generics Without the Pain, Part 1"(developerWorks, February 2003) explains the purpose and benefits of Javagenerics.

• "Java Generics Support in Eclipse 3.1" (developerWorks, October 2005)demonstrates Eclipse 3.1's extensive support of generics.

• The Eclipse 3.1.1 release notes enumerate the list of bugs fixed in the EclipseV3.1.1 maintenance release.

• "Developing Eclipse plug-ins" explains the architecture of Eclipse and describeshow to extend the Eclipse platform with your own set of plug-ins.

• The Eclipse 3.1.1. regression tests detail the performance and veracity of EclipseV3.1.1.

• Expand your Eclipse skills by visiting IBM developerWorks Eclipse projectresources.

• Visit the developerWorks Open source zone for extensive how-to information,tools, and project updates to help you develop with open source technologies anduse them with IBM's products.

Get products and technologies

• The Ruby Development Tool is an open source integrated developmentenvironment for Ruby based on Eclipse.

• Get the J2SE 5.0 SDK.

• Download the Java 2 Platform Standard Edition 5.0 Runtime (JRE).

• Innovate your next open source development project with IBM trial software,available for download or on DVD.

Discuss

• The Eclipse newsgroups has lots of resources for people interested in using and

ibm.com/developerWorks developerWorks®

Explore the new features of Eclipse V3.1© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 29 of 30

extending Eclipse.

• Get involved in the developerWorks community by participating indeveloperWorks blogs.

About the author

Martin StreicherMartin Streicher is the editor-in-chief of Linux Magazine. He earned a master's degreein computer science from Purdue University and has been programming UNIX-likesystems since 1982 in the Pascal, C, Perl, Java, and (most recently) Rubyprogramming languages.

developerWorks® ibm.com/developerWorks

Explore the new features of Eclipse V3.1Page 30 of 30 © Copyright IBM Corporation 1994, 2008. All rights reserved.