Quantcast
Channel: Oracle Bloggers
Viewing all articles
Browse latest Browse all 19780

How to Define the Content of Generated Methods in NetBeans IDE

$
0
0

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):

@Override
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.


Viewing all articles
Browse latest Browse all 19780

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>