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.

2 thoughts on “Eclipse Tip: Auto-generate compilation units by pasting snippets

Comments are closed.