Eclipse Tip: Auto-generate compilation units by pasting snippets

When I am trying out some new library or technique I like to pick a sample code and try it out. I am sure a lot of you do it too. I have a test project for this. But it is always a pain to create a new type, paste the code, change the package, type name…

Well with Eclipse 3.2 it is all to easy. Here is how to do it.

1. Copy the following code (or any code just make sure it has the type declaration too)

public class EclipseRocks {
    public static void main(String[] args) {
        System.out.println(“Eclipse Rocks!”);
    }
}

2. Go to the Package Explorer.

3. Select the package you want to add the sample to.

4. Paste the code.

5. Well that’s it you are done. :-)

Eclipse creates the compilation unit for you. It names the file based on the type and corrects/adds the package statement. Now you are good to go.

Nice another time saving feature from Eclipse. In Eclipse 3.3 this feature is further extended. If you do not select anything in the Package Explorer, Eclipse creates a new project for you.

Update: Changed the code listing. The line numbers should not have been there plus the formatting was messed up in feed readers. Thanks for the heads up Alex Blewitt.

Vasanth Dharmaraj is a Java Architect currently working for Western Union living in the Bay Area. He is interested in programming, gadgets, formula one... You can follow him on Twitter.

Posted in Eclipse, Java, Software
2 comments on “Eclipse Tip: Auto-generate compilation units by pasting snippets
  1. Alex Blewitt says:

    Neat. Pity you’ve got the line numbers in theprintout; I’m assuming that it wouldn’t work with line numbers in?

    Also, the feed didn’t deal with the code that well … see how it appears on Planet Eclipse (http://www.planeteclipse.org/planet/)

    Alex.

  2. Vasanth says:

    I just fixed it based on your comments.

Ads By Google