• Share this article:

More code templates in Eclipse

Tuesday, February 28, 2006 - 08:57 by Wayne Beaton

How about this…

Start typing the name of a method (where a method should go). Don’t worry about the return type or anything else, just the name. Hit ctrl-space. Eclipse will offer to build a new private method with that name. Type “main” and hit ctrl-space and it will build you a new main method stub (complete with all the necessary parameters and return types).

Or… highlight a few lines of code in an existing method and hit ctrl-space. Down near the bottom of suggestions are a few interesting ones, including “do”, “for”, “if”, “runnable”, and others. Select one of these and it will wrap the selected code with a “do” loop, “for” loop, and so on. “Runnable is my favourite; it wraps the code in a new instance of java.lang.Runnable instance.

So…


private void whatDoYouGetWhenYouMultiplySixByNine() {
doSomething();
doSomethingElse();
}

becomes…


private void whatDoYouGetWhenYouMultiplySixByNine() {
new Runnable() {
public void run() {
doSomething();
doSomethingElse();
}
}
}

The best part is that if you look at how these templates are defined, it’s pretty easy to sort out how to define your own. More on that later…