You can create various Java code templates in Eclipse via
Window > Preferences > Java > Editor > Templates
e.g.
sysout
is expanded to:
System.out.println(${word_selection}${});${cursor}
You can activate this by typing sysout
followed by CTRL+SPACE
What useful Java code templates do you currently use?
Include the name and description of it and why it's awesome.
There's an open bounty on this for an original/novel use of a template rather than a built-in existing feature.
- Create Log4J logger
- Get swt color from display
- Syncexec - Eclipse Framework
- Singleton Pattern/Enum Singleton Generation
- Readfile
- Const
- Traceout
- Format String
- Comment Code Review
- String format
- Try Finally Lock
- Message Format i18n and log
- Equalsbuilder
- Hashcodebuilder
- Spring Object Injection
- Create FileOutputStream
For
log
, a helpful little ditty to add in the member variable.Format a string
MessageFormat - surround the selection with a MessageFormat.
This lets me move a cursor to a string, expand the selection to the entire string (Shift-Alt-Up), then Ctrl-Space twice.
Lock the selection
lock - surround the selected lines with a try finally lock. Assume the presence of a lock variable.
NB
${line_selection}
templates show up in the Surround With menu (Alt-Shift-Z).Invoke code on the GUI thread
I bind the following template to the shortcut
slater
to quickly dispatch code on the GUI thread.strf -> String.format("msg", args)
pretty simple but saves a bit of typing.Create a mock with Mockito (in "Java statements" context):
And in "Java type members":
Mock a void method to throw an exception:
Mock a void method to do something:
Verify mocked method called exactly once:
Verify mocked method is never invoked:
New linked list using Google Guava (and similar for hashset and hashmap):
Also I use a huge template that generates a Test class. Here is a shortened fragment of it that everyone interested should customize:
When testing around with code I sometimes missed out on deleting some syso s. So I made myself a template called syt.
Before I compile I always check my TODOs and will never forget to delete a System.out again.