Geertjan's Blog

  • May 5, 2014

How to Define the Content of Generated Methods in NetBeans IDE

Geertjan Wielenga
Product Manager

Here's a small and interesting corner of NetBeans IDE functionality. Let's say you have a class like this, i.e., you're extending some other class and the IDE presents to you the hint to implement all the abstract methods:

So you go ahead with the hint and end up with methods that look as follows:

Each of the methods above looks, in full, as follows (I added the linebreak, for readability):

public String getWord(int idx) {
    throw new UnsupportedOperationException("Not supported yet.");
//To change body of generated methods, choose Tools | Templates.

Wouldn't it be cool if you'd be able to tell the IDE what the body of a generated method should contain?

Well, go to Tools | Templates and then find the very hidden subcategory Java | Code Snippets and you'll see the following:

Select either of the two above, for example, the "Generated Method Body" template, and then choose "Open in Editor", which will become enabled if one of these templates is selected, and then the Source Editor shows the following:

In other words, above you see that you can redefine the body of generated methods, using FreeMarker to do so, together with some handy variables that the IDE provides for this purpose.

For example, let's delete that complete throw statement and replace it with the following:

return ${default_return_value};

As soon as you have saved your change, the IDE will use it. So immediately let the IDE generate the methods again and you'll see this, instead of the throw statements:

Of course, there's a reason why the throw statements are created, since they're easy to identify and throw errors when invoked, i.e., you have clear reminders of where to go to add your code. If you follow my instructions above, you'll have no idea which parts were generated vs. which parts you already worked on and customized. However, the point here is to simply show that you can change generated method bodies, should you want/need to do so.

Similarly, change the "Overridden Method Body" template if you want the IDE to generate custom content when it creates overridden methods, via the Source | Insert Code | Override Method code generator.

Join the discussion

Comments ( 2 )
  • Lolmewn Saturday, May 31, 2014

    return ${default_return_value}; does seem to mess up any 'void' methods, since they shouldn't return anything. Is there a work-around for this?

  • Neal Monday, February 6, 2017

    Here's a sensible default implementation. Oracle dropped the ball on this one. ��

    <#if method_return_type?? && method_return_type != "void">

    return ${default_return_value}; // Generated Method Body (see Tools>Templates)


    return; // Generated Method Body (see Tools>Templates)


Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.