ONJava.com    
 Published on ONJava.com (http://www.onjava.com/)
 See this if you're having trouble printing code examples


O'Reilly Book Excerpts: Eclipse

Java Development on Eclipse, Part 1

by Steve Holzner

Author's note: In part one of a two-part series of excerpts from Eclipse's Chapter 2, we'll get down to the business of developing Java using Eclipse. We're going to take a look at using Eclipse for Java development as well as project management, going from the basics to the fairly serious. Nearly everything in this chapter is essential knowledge for the Java developer using Eclipse, so let's jump in.

Developing Java Code

If there's anything that takes more time than it seems to be worth in Java, it's creating code from scratch. While the logic inside a method, interface, or class is unique, the modifiers of a method, the imports for a class, and the syntax involved with new packages is the same over and over again. This often results in a lot of repetitive typing, wasted time, and in many cases, annoying little typo-related bugs. Eclipse can help with all this and more.

Eclipse

Related Reading

Eclipse
By Steve Holzner

Creating New Methods

Eclipse - through code assist - makes it easy to create new methods. As an example, we're going to create and call a new method named printer, which displays the message "No worries.", as you can see in Example 2-1.

Example 2-1. The Ch02_01.java example

public class Ch02_01
{
    public static void main(String[] args)
    {
        printer( );
    }

    private static void printer( )
    {
        System.out.println("No worries.");
    }
}

How do you create new methods? Start Eclipse now and create a new project named Ch02_01. Then create a new Java class named Ch02_01, making it part of the org.eclipsebook.ch02 package. Leave the checkbox for the creation of a stub for the main method checked when you create this new class. This gives you the code:

public class Ch02_01 {

        public static void main(String[] args) {
        }
}

You could simply type in the printer method, of course, but Eclipse can also be of assistance here. Move the cursor below the body of the main method and type private to make this new method a private method, and then type Ctrl+Space to open code assist, as you see in Figure 2-1.

Figure 2-1
Figure 2-1. Creating a private method

Code assist lets you select the type of private method you want to create private, private static, and so on. Here, select the private static method, creating the new method template you see in Figure 2-2. The placeholder return_type is highlighted, ready for you to enter in a type; use void. Next, replace the name placeholder with the name printer and delete the arguments placeholder.

Figure 2-2
Figure 2-2. Setting the new method's return type

This creates the new method in outline; all that's left is to add the code that will display the message (as before, you can take advantage of code assist to pause after you type each dot for suggestions):

public static void main(String[] args) {
}

private static void printer( )
{
    System.out.println("No worries.");
}

Then just add the call to printer from main:

public static void main(String[] args) {
    printer( );
}

private static void printer( )
{
    System.out.println("No worries.");
}

That's all you need; now you can run the example with the Run As→ Java Application menu item. You should see "No worries." appear in the Console view just as before. But this time, we're using a new custom method.

Creating New Classes

We've created a new method and given it a name, but what if you want that new method to be in a different class? For example, say that your main method is in a class named Ch02_02, but the printer method is in a class named Ch02_02Helper:

Ch02_02
|
+--------main

Ch02_02Helper
|
+--------printer

In this case, you could create a new object of the Ch02_02Helper class in the main method, and then you could call that object's printer method, as you see in Example 2-2.

Example 2-2. The Ch02_02.java example

public class Ch02_02 {
        public static void main(String[] args) {
                Ch02_02Helper helper = new Ch02_02Helper( );
                helper.printer( );
        }

The Ch02_02Helper class, with the printer method in it, appears in Example 2-3.

Example 2-3. The Ch02_02Helper.java example

public class Ch02_02Helper {
        public void printer( ) {
                System.out.println("No worries.");
        }
}

To implement this example with its two classes in Eclipse, create a new project named Ch02_02 and add the new class Ch02_02Helper to the project. Make this class public and put it into the org.eclipsebook.ch02 package (and make sure that you don't create a main method stub in this class). Next, add the printer method to this class, as in Example 2-2.

Then save the file. This is an important step because if you don't save the file, the printer method won't be available to the rest of your project's code. This is essential to know whenever you want to work with items from file A in file B, you have to save file A first because Eclipse compiles from the files, not what's in its editors.

Having created the new Ch02_02Helper class, the next step is to create the class containing code that will make use of it, the Ch02_02 class. Create that new class in the project and add a stub for the main method to it. Now all you need to do in the main method is add the code to create an object of the Ch02_02Helper class and call that object's printer method:

public class Ch02_02 {
   public static void main(String[] args) {
      Ch02_02Helper helper = new Ch02_02Helper( );helper.printer( );
   }

Then save all your work and run the application; Eclipse's compiler handles locating both classes in the same package for you. You should see the "No worries." message as shown in Figure 2-3. As you can see in the Package Explorer, we're using multiple classes in the same project.

Figure 2-3
Figure 2-3. Using multiple classes

And there's more you can do with multiple classes here as well. Say you want to override the printer method and change the text it displays. You can do that by deriving a new class based on the Ch02_02Helper class and overriding printer in this new class. To do this, right-click the org.eclipsebook.ch02 package inside the Ch02_02 project and select the New→ Class item, opening the New Java Class dialog you see in Figure 2-4.

Figure 2-4
Figure 2-4. Creating a derived class

Name the new class Ch02_02HelperHelper, enter the package name, and deselect the main stub checkbox. To derive this class from Ch02_02Helper, type Ch02_02Helper in the Superclass box (you can also implement interfaces by entering them into the Interfaces box), and click Finish to create the new class. Here's what you get - this new class automatically extends the Ch02_02Helper class:

public class Ch02_02HelperHelper extends Ch02_02Helper {

}

TIP: Notice the "Enclosing type" box in the New Java Class dialog. If you want to enclose one class within another, you can enter the name of the enclosing class here. Note also that if you right-click the enclosing class in the Package Explorer and select New→ Class, the enclosing class's name will appear in the Enclosing type text box when this dialog opens, although it won't be used unless you select its checkbox.

We want to override the printer method from the base class's version here, so open the new class, Ch02_02HelperHelper, and select the Source→ Override/Implement Methods menu item, opening the Override/Implement Methods dialog box you see in Figure 2-5 (if you're implementing an interface, you can also find the methods you have to implement here).

Figure 2-5
Figure 2-5. Overriding a method

This dialog shows a list of possible overrides; all you have to do is pick one. In this case, select the printer method and click OK. When you do, you'll see a stub for the new version of the printer method in the Ch02_02HelperHelper class:

public class Ch02_02HelperHelper extends Ch02_02Helper {

        /* (non-Javadoc)
         * @see org.eclipsebook.ch02.Ch02_02Helper#printer( )
         */
        public void printer( ) {// TODO Auto-generated method stubsuper.printer( );}

}

In this overriding version, use this code to display a new message, "No problems.":

public void printer( ) {
        System.out.println("No problems.");
}

And that's it - you've overridden a method in a derived class. As the final step here, change the code in the main method to use your new class:

public class Ch02_02 {

        public static void main(String[] args) {
                Ch02_02HelperHelper helper = new Ch02_02HelperHelper( );
                helper.printer( );
        }
}

When you run this example, you should see the new message, "No problems.", as in Figure 2-6.

Figure 2-6
Figure 2-6. Using our derived class

As you can see, automatic code generation can be a timesaver. In this case, you used it to override a method, but there are other options available in the Source menu:

For example, say you've stored the message that the printer method displays in a class field named message:

public class Ch02_02HelperHelper extends Ch02_02Helper {

        /* (non-Javadoc)
         * @see org.eclipsebook.ch02.Ch02_02Helper#printer( )
         */

    String message = "No problems.";
        
        public void printer( ) {
                System.out.println(message);
        }

Instead of simply storing this data in a class field, you can use getter and setter methods to access it (these methods are of the standard form used in JavaBeans to support properties). In this case, you can create getter and setter methods for the value in message by selecting the Source→ Generate Getter and Setter menu item, which opens the Generate Getter and Setter dialog box you see in Figure 2-7. Just select the checkbox next to message and click OK.

Figure 2-7
Figure 2-7. Creating Getter and Setter methods

Eclipse will create the new getter and setter methods getMessage and setMessage; we can use getMessage when we want to display the message in the printer method this way:

public class Ch02_02HelperHelper extends Ch02_02Helper {

        /* (non-Javadoc)
         * @see org.eclipsebook.ch02.Ch02_02Helper#printer( )
         */

        String message = "No problems.";
        
        public void printer( ) {
                System.out.println(getMessage( ));
        }

        /**
         * @return
         */
        public String getMessage( ) {
                return message;
        }

        /**
         * @param string
         */
        public void setMessage(String string) {
                message = string;
        }

Another good timesaver is the Source→ Surround with try/catch Block menu item. This one checks the code you've selected for uncaught exceptions and writes a try/catch block for any that it finds - another great Eclipse feature worth the price of admission.

Creating New Packages

Besides using multiple classes in the same project, it's also easy to distribute your code over multiple packages in the same project. For example, you can break up your code into two packages, org.eclipse.ch02 and org.eclipse.ch02_2, as you can see in the Package Explorer at left in Figure 2-8. Here, we're putting the Ch02_03Helper class, which contains the printer method, into an entirely new package, org.eclipse.ch02_2.

Figure 2-8
Figure 2-8. Using multiple packages

If you want to access a class in another package, just remember to import it - in this case, that means using the fully qualified name of the class you want access to, which is org.eclipsebook.ch02_2.Ch02_03Helper. After you've imported the class, you can create objects using it, like this:

import org.eclipsebook.ch02_2.Ch02_03Helper;

/**
 * @author Steven Holzner
 *
 * To change the template for this generated type comment go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
public class Ch02_03 {

        public static void main(String[] args){
                Ch02_03Helper helper = new Ch02_03Helper( );
                helper.printer( );
        }
}

And that's all it takes; as you can see, multiple packages in the same project are no problem at all.

What if the code you want to use is not only in a different package, it's also in another project? When you create a project, you have the option of adding other projects to the build path. For example, if you want to create a new project that works with the code in the org.eclipsebook.ch02_2 package from a new project, Ch02_03, just click the Projects tab in the second pane of the New Java Project dialog and add the Ch02_03 project to the build path, as you see in Figure 2-9.

Figure 2-9
Figure 2-9. Adding a project to the build path

Now the code in Ch02_03, including the org.eclipsebook.ch02_2 package, is accessible to your new project. You can also add other projects to the build path after a project has been created by selecting the project in the Package Explorer, right-clicking it, and selecting the Properties context menu item. In the Properties dialog that opens, select Java Build Path and click the Projects tab, giving you the same display as in Figure 2-9.

Building and Running Code

How do you create the Java .class files that are the end result of developing a project? You use the items in the Project menu. The main menu item here is the Project→ Build Project menu item. This item will compile the source code files in your project and leave the resulting .class files in the same folder as the source code files by default. For example, if you are working with the Ch02_03 project and select Project→ Build Project, the .class files for this project will appear in the directory workspace/Ch02_03/org/eclipsebook/Ch02 (recall that the classes in this project are in the org.eclipsebook.Ch02 package, which the directory structure reflects). Once created, these .class files are ready for use and distribution.

It often makes sense to store all your project's source code in a folder named src and the binary output in a folder named bin. If you want to set things up this way when you create a new project, open the New Java Project dialog as usual, and, in the second pane, click the Source tab followed by the Add Folder button. Doing so opens the Source Folder Selection dialog; click the Create New Folder button and give the new folder the name src. Then click OK twice. Eclipse will recognize that you're creating a source code folder and automatically ask if you want to create a bin folder for the binary output, as you see in Figure 2-10.

Figure 2-10
Figure 2-10. Creating source and bin folders

Configuring a project this way automatically stores your source code in the folder named src and the binary output in a folder named bin (bin will not appear in the Package Explorer because it doesn't contain any source code).

Using JAR and .class Files

Say that you're writing a Java servlet (for more details on servlets, see Chapter 9), shown in Example 2-4.

Example 2-4. The Ch02_04.java example

package org.eclipse.ch02;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * @author Steven Holzner
 *
 * To change the template for this generated type comment go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */

public class Ch02_04 extends HttpServlet {

        public void doGet(HttpServletRequest request,
                HttpServletResponse response)
                throws IOException, ServletException
        {
                response.setContentType("text/html");
                PrintWriter out = response.getWriter( );

                out.println("<HTML>");
                out.println("<HEAD>");
                out.println("<TITLE>");
                out.println("A Web Page");
                out.println("</TITLE>");
                out.println("</HEAD>");
                out.println("Hello there!");
                out.println("</BODY>");
                out.println("</HTML>");
        }
}

The code in this example relies on classes like HttpServlet that don't come built into the Java core libraries. Since Eclipse can't find some of the required classes, you'll see plenty of wavy red underlines as you enter this code, as in Figure 2-11.

Figure 2-11
Figure 2-11. Plenty of import not found errors

You can fix this easily by including the correct Java Archive (JAR) file in the classpath, which, in this case, is servlet.jar. This JAR file comes with the web server we're going to use later in the book, Apache Tomcat. To add servlet.jar to the classpath, right-click the project in the Package Explorer and select the Properties item, opening the dialog you see in Figure 2-12.

Figure 2-12
Figure 2-12. The Properties dialog

In this case, you select the Libraries tab in this dialog, click Add External JARs, navigate to servlet.jar, and click OK. Doing so adds servlet.jar to the classpath, as you see in Figure 2-12. Click OK to close the Properties dialog and build the project; when you do, things work out fine, as you can see in Figure 2-13, because the needed JAR file is now in the classpath - you can see the reference to servlet.jar in this project in the Package Explorer at left.

Figure 2-13
Figure 2-13. A new JAR file in the build path

If you know you're going to be using a JAR file like servlet.jar when you first create the project, you can add that JAR file to the project's classpath in the third pane of the New Project dialog. You'll see the same tabs there as you do in Figure 2-12 - just click the Libraries tab and add any JAR files you want to the project.

If you add multiple JAR files to the classpath, you can also indicate the order in which you want them searched - just select the Order and Export tab in the Properties dialog, as you see in Figure 2-14, and change the order of imported items with the Up and Down buttons. You can also indicate which items to export by selecting their checkboxes here; when you export an item, it becomes available to any project dependent on the current project.

Figure 2-14
Figure 2-14. Setting import order

You can also add .class files to the classpath - just use the Add Class Folder button in the Properties dialog to add a folder containing .class files.

Say that you're going to be developing more than one servlet; in this case, you might want to make things easier on yourself by creating a classpath variable corresponding to servlet.jar. You can use that variable to add servlet.jar to the classpath. To create a classpath variable, select Window→ Preferences, then select the Java item's Classpath Variables item, as you see in Figure 2-15. To create a new variable, click New, enter the new variable's name - we'll use SERVLET_LIB here - and the path it corresponds to, then click OK. You can see this new variable in Figure 2-15.

Figure 2-15
Figure 2-15. Creating a classpath variable

Now, when you want to add this classpath variable to a project's classpath, just open the project's Properties dialog, click the Libraries tab, click the Add Variable button that you see in Figure 2-12, and select the variable you want to add to the classpath. Using classpath variables like this is not only convenient, but it also centralizes your classpath references - for example, if you want to use a new version of servlet.jar, all you've got to do is update the classpath variable.

Setting the Launch Configuration

Say that your code needs to read command-line arguments, as you see in Example 2-5, where we're displaying the first word passed on the command line to our code. For example, you could start this program on the command line like this: %javaCh02_05Hello! (we'll use % for a generic command-line prompt in this book), and you'd expect the program to display the word "Hello!"

Example 2-5. The Ch02_05.java example

package org.eclipsebook.ch02;

/**
 * @author Steven Holzner
 *
 * To change the template for this generated type comment go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
public class Ch02_05 {

        public static void main(String[] args) {
                System.out.println(args[0]);
        }
}

Unfortunately, when you run this code as is, you'll get the error java.lang.ArrayIndexOutOfBoundsExceptionatorg.eclipsebook.ch02.Ch02_05.main(Ch02_05.java:18) in the console window because we haven't supplied any command-line arguments to be stored in the args array. You can supply command-line arguments in the launch configuration for this project; to set that configuration, select the Run→ Run . . . menu item, opening the Run dialog you see in Figure 2-16.

Figure 2-16
Figure 2-16. Setting a launch configuration

In this dialog, enter "Hello!" in the Program arguments box, as you see in Figure 2-16. If you want to, you can also enter Java Virtual Machine options in the VM arguments box here, as well as select what Java runtime environment you want to work with by clicking the JRE tab. After you enter "Hello!" in the Program arguments box, click Run and the code in your project will read that command-line argument and display it, as you see in Figure 2-17.

Figure 2-17
Figure 2-17. Supplying command-line arguments to a program

Selecting the Java Runtime

When you run Eclipse for the first time, it searches for installed Java runtimes, and it may not use the one you want it to use. For example, Eclipse may want to use the outdated JRE that came with your browser instead of the brand new Java SDK you've just downloaded. You can specify what Java runtime you want Eclipse to use by selecting Window→ Preferences, selecting Installed JREs, and selecting the one you want, as shown in Figure 2-18 (use the Add button to add JREs and SDKs).

Figure 2-18
Figure 2-18. Selecting a JRE

Next week, in part two in this two-part series excerpted from Eclipse: The Definitive Guide, author Steve Holzner covers creating Javadocs, refactoring, adding certain skills to your Eclipse toolbox, and customizing the development environment.

Steve Holzner is the author of O'Reilly's upcoming Eclipse: A Java Developer's Guide.


Return to ONJava.com.

Copyright © 2009 O'Reilly Media, Inc.