NetBeans IDE: Custom hints

Another mostly unnoticed but powerful feature of NetBeans is the possibility of creating custom hints.

Custom hints (a.k.a custom inspections or quickfixes in other IDEs) are available since NetBeans 7.1. They match patterns in Java code and can provide a transformation. This enables you to create small refactorings based on the AST without coding. A typical usecase is the type-safe migration of API – instead of the error-prone plain text-based “search and replace” approach.

You can create your own hint in a special DSL as described in [1],[2],[3]. Geertjan already blogged several times about this topic at [4] and [5]. Yes, the UI for creating/enabling the hints is not very intuitive, but it works.

The best thing is the integration in the editor:

Your custom hints

  • are available in the Java editor like the “standard” hints 2013-02-12_23h45_13
  • can be applied to a file/package/project or even all opened projects. It includes also a changes-preview. This is pretty useful to do apply transformations in a batch.2013-02-12_23h44_25

Here some very basic examples:

<!description=&quot;Convert to assertTrue/assertFalse&quot;>
org.junit.Assert.assertEquals(true, $any)
=> org.junit.Assert.assertTrue($any)
org.junit.Assert.assertEquals($msg, true, $any)
=> org.junit.Assert.assertTrue($msg, $any)
org.junit.Assert.assertEquals(false, $any)
=> org.junit.Assert.assertFalse($any)
org.junit.Assert.assertEquals($msg, false, $any)
=> org.junit.Assert.assertFalse($msg, $any)
<!description=&quot;Remove dead if-branch&quot;>
if (false){
<!description=&quot;Add extra parenthesis&quot;>
$a && $b
($a) && ($b)
$a || $b
($a) || ($b)
<!description=&quot;Flip operands&quot;>
$a & $b
$b & $a
$a && $b
$b && $a
$a || $b
$b || $a
<!description=&quot;Flip &lt; &gt;&quot;>
$a < $b =>
$b > $a
$a > $b
$b < $a
<!description="JUL to SLF4J">
$$msg) :: $jul instanceof java.util.logging.Logger && $msg instanceof java.lang.String

Those patterns can also be used to code more advanced hints [7] [8].

Give it a try and share your patterns! Which selfmade hints do you use on a regular basis?

FYI: Intellj IDEA provides a similar feature called “structural replace” [9]

Update from 2015/02: Added new links






Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s