518

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.

I am looking 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
halfer
  • 18,701
  • 13
  • 79
  • 158
Jon
  • 55,763
  • 30
  • 120
  • 149
  • 5
    Are there any that generate a switch statement from an Enum with all possible cases? I know you can do this with CTRL+1, but I'd rather use cmd completion. – GreenKiwi Sep 22 '11 at 17:21
  • 4
    Can you explain what `System.out.println(${word_selection}${});${cursor}` means? It sounds like there's a way to select a word and automatically encase it inside a `sysout` call, am I right? How? – CodyBugstein May 14 '13 at 18:34
  • 3
    you highlight the word you want surrounded by sysout call and press Ctrl-Space (then typing in the name of the template if you have lots of highlight aware templates) – JReader Aug 19 '14 at 20:22
  • @JReader what does the ${} do? – Roland Feb 15 '17 at 08:43

46 Answers46

426

The following code templates will both create a logger and create the right imports, if needed.

SLF4J

${:import(org.slf4j.Logger,org.slf4j.LoggerFactory)}
private static final Logger LOG = LoggerFactory.getLogger(${enclosing_type}.class);

Log4J 2

${:import(org.apache.logging.log4j.LogManager,org.apache.logging.log4j.Logger)} 
private static final Logger LOG = LogManager.getLogger(${enclosing_type}.class); 

Log4J

${:import(org.apache.log4j.Logger)}
private static final Logger LOG = Logger.getLogger(${enclosing_type}.class);

Source.

JUL

${:import(java.util.logging.Logger)}
private static final Logger LOG = Logger.getLogger(${enclosing_type}.class.getName());
Joost
  • 3,030
  • 2
  • 23
  • 37
Robert Munteanu
  • 63,405
  • 31
  • 191
  • 270
49

Some additional templates here: Link I - Link II

I like this one:

readfile

 ${:import(java.io.BufferedReader,  
           java.io.FileNotFoundException,  
           java.io.FileReader,  
           java.io.IOException)}  
 BufferedReader in = null;  
 try {  
    in = new BufferedReader(new FileReader(${fileName}));  
    String line;  
    while ((line = in.readLine()) != null) {  
       ${process}  
    }  
 }  
 catch (FileNotFoundException e) {  
    logger.error(e) ;  
 }  
 catch (IOException e) {  
    logger.error(e) ;  
 } finally {  
    if(in != null) in.close();  
 }  
 ${cursor} 

UPDATE: The Java 7 version of this template is:

${:import(java.nio.file.Files,
          java.nio.file.Paths,
          java.nio.charset.Charset,
          java.io.IOException,
          java.io.BufferedReader)}
try (BufferedReader in = Files.newBufferedReader(Paths.get(${fileName:var(String)}),
                                                 Charset.forName("UTF-8"))) {
    String line = null;
    while ((line = in.readLine()) != null) {
        ${cursor}
    }
} catch (IOException e) {
    // ${todo}: handle exception
}
RevanthKrishnaKumar V.
  • 1,779
  • 1
  • 19
  • 33
Jon
  • 55,763
  • 30
  • 120
  • 149
  • 48
    i think this is what a method is for :) – benmmurphy Jul 06 '09 at 13:37
  • 3
    Err I think you've missed the point... saying that I actually don't know what your point is... it's about code generation not modularity... – Jon Jul 06 '09 at 16:12
  • 21
    I think the point is that adding this much code in a template is cut-and-paste programming for a very common situation. – Scott McIntyre Jun 10 '11 at 15:23
  • i think he was being cynical on purpose but I could be wrong as this is the internet. – KJW Feb 21 '12 at 10:15
  • This stuff is on github.com, https://github.com/sharfah/dotfiles/blob/master/.eclipse/templates.xml, and you can import it into Eclipse by choosing Preferences/Java/Editor/Templates – knb Aug 16 '12 at 07:35
  • 6
    Yes, you should use a utility method to read a file instead of pasting blocks of code. Write a method yourself, or use Apache commons-io IOUtils. Still, if you make lots of throwaway projects with different classpaths, it can be a pain to add a JAR or link in your utility class just to read a file. Sometimes you just need to write some throwaway code that reads a file, and get on with your life. – Mike Clark Sep 26 '13 at 01:07
  • 1
    In Java 7, prefer `StandardCharsets.UTF_8` over `Charset.forName("UTF-8")`. – Mike Clark Sep 26 '13 at 01:09
  • 1
    utility method, or direct pasting of code block into your own methods, either way, you're still doing this. if you don't, you are violating some core practices in secure programming. risking resource leaks, etc. So you create your read file function, then you have to write it.. this template does that for you. I fail to see the relevance of the critique of the template and how the template applies to implementation technique. – Armand Mar 13 '15 at 19:24
33

Format a string

MessageFormat - surround the selection with a MessageFormat.

 ${:import(java.text.MessageFormat)} 
 MessageFormat.format(${word_selection}, ${cursor})

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.

${lock}.acquire();
try {
    ${line_selection}
    ${cursor}
} finally {
    ${lock}.release();
}

NB ${line_selection} templates show up in the Surround With menu (Alt-Shift-Z).

jamesh
  • 18,935
  • 13
  • 54
  • 96
  • I use this one combined with log statements : logger.info(MessageFormat.format(${word_selection}, ${cursor}); – Pierre Henry Oct 22 '12 at 09:23
  • The methods for acquiring and releasing locks are called `lock` and `unlock`. `acquire` and `release` are used for semaphores and [their use within a try-finally block is not as strongly advised as with locks](http://stackoverflow.com/questions/9117048/why-it-isnt-advised-to-call-the-release-method-of-a-binary-semaphore-from-ins). – Marco Lackovic Mar 10 '14 at 10:39
  • Ctrl+Space twice doesn't seem to work any more, brings up SWT templates. Is there a replacement? – Noumenon Dec 10 '19 at 22:44
28

Append code snippet to iterate over Map.entrySet():

Template:

${:import(java.util.Map.Entry)}
for (Entry<${keyType:argType(map, 0)}, ${valueType:argType(map, 1)}> ${entry} : ${map:var(java.util.Map)}.entrySet())
{
    ${keyType} ${key} = ${entry}.getKey();
    ${valueType} ${value} = ${entry}.getValue();
    ${cursor}
}

Generated Code:

for (Entry<String, String> entry : properties.entrySet())
{
    String key = entry.getKey();
    String value = entry.getValue();
    |
}

Screenshot

Community
  • 1
  • 1
mmdemirbas
  • 8,486
  • 5
  • 44
  • 51
  • 1
    Like your pic, it shows me you can use a variable in `${}` and that, instead of `${cursor}`, enables "tab iteration" between fields. Thanks. – WesternGun Aug 30 '18 at 08:57
28

I know I am kicking a dead post, but wanted to share this for completion sake:

A correct version of singleton generation template, that overcomes the flawed double-checked locking design (discussed above and mentioned else where)

Singleton Creation Template: Name this createsingleton

static enum Singleton {
    INSTANCE;

    private static final ${enclosing_type} singleton = new ${enclosing_type}();

    public ${enclosing_type} getSingleton() {
        return singleton;
    }
}
${cursor}


To access singletons generated using above:

Singleton reference Template: Name this getsingleton:

${type} ${newName} = ${type}.Singleton.INSTANCE.getSingleton();
pentaphobe
  • 317
  • 1
  • 4
  • 8
questzen
  • 3,140
  • 16
  • 21
  • 4
    It's not dead, it's community wiki, so it makes sense to add more templates to it as you find them. There's not really a comprehensive set of these anywhere else... – Jon Jul 15 '10 at 17:07
  • Jon, the time gap between the earlier post and my post was nearly 8 months, thats what compelled to quote so. I couldn't phrase it better than your comment :) – questzen Jul 23 '10 at 13:10
  • When I create this as part of a class (a nested enum in a class) I get the name of the class as `${enclosing_type}` - intended ? – Mr_and_Mrs_D Jun 04 '12 at 23:30
  • 1
    @Mr_and_Mrs_D, I think that is the point. You get a singleton instance of the class in which you put this template. Now all you need to do is make the enclosing type constructor(s) private and have a pretty safe singleton generator. – Mike Adler Jun 06 '12 at 07:29
  • If you want to use this to create an enum use `${primary_type_name}` example: `public enum ${primary_type_name} { INSTANCE; private ${return_type} ${name} = new ${return_type}(); public ${return_type} ${getName}(${}) { return ${name}; } ${cursor} }` – Robert Smit Sep 10 '15 at 15:09
25

For log, a helpful little ditty to add in the member variable.

private static Log log = LogFactory.getLog(${enclosing_type}.class);
cgp
  • 39,478
  • 10
  • 96
  • 129
  • For writing to a log file manually: ${:import(java.io.PrintWriter, java.io.BufferedWriter, java.io.FileWriter)} try { PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(${logFile:var(String)}, true))); out.println(${logLine:var(String)}${cursor}); out.close(); } catch (IOException e) { /* TODO: exception handling */ e.printStackTrace(); } – Jack Miller Feb 26 '15 at 10:30
24

Create a mock with Mockito (in "Java statements" context):

${:importStatic('org.mockito.Mockito.mock')}${Type} ${mockName} = mock(${Type}.class);

And in "Java type members":

${:import(org.mockito.Mock)}@Mock
${Type} ${mockName};

Mock a void method to throw an exception:

${:import(org.mockito.invocation.InvocationOnMock,org.mockito.stubbing.Answer)}
doThrow(${RuntimeException}.class).when(${mock:localVar}).${mockedMethod}(${args});

Mock a void method to do something:

${:import(org.mockito.invocation.InvocationOnMock,org.mockito.stubbing.Answer)}doAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock invocation) throws Throwable {
    Object arg1 = invocation.getArguments()[0];
    return null;
}
}).when(${mock:localVar}).${mockedMethod}(${args});

Verify mocked method called exactly once:

${:importStatic(org.mockito.Mockito.verify,org.mockito.Mockito.times)}
verify(${mock:localVar}, times(1)).${mockMethod}(${args});

Verify mocked method is never invoked:

${:importStatic(org.mockito.Mockito.verify,org.mockito.Mockito.never)}verify(${mock:localVar}, never()).${mockMethod}(${args});

New linked list using Google Guava (and similar for hashset and hashmap):

${import:import(java.util.List,com.google.common.collect.Lists)}List<${T}> ${newName} = Lists.newLinkedList();

Also I use a huge template that generates a Test class. Here is a shortened fragment of it that everyone interested should customize:

package ${enclosing_package};

import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.junit.runner.RunWith;

// TODO autogenerated test stub
@RunWith(MockitoJUnitRunner.class)
public class ${primary_type_name} {

    @InjectMocks
    protected ${testedType} ${testedInstance};
    ${cursor}

    @Mock
    protected Logger logger;

    @Before
    public void setup() throws Exception {
    }

    @Test
    public void shouldXXX() throws Exception {
        // given

        // when
        // TODO autogenerated method stub

        // then
        fail("Not implemented.");
    }
}
// Here goes mockito+junit cheetsheet
ItamarG3
  • 3,846
  • 6
  • 28
  • 42
mantrid
  • 2,779
  • 18
  • 17
  • 1
    I'm curious: why would you need to mock the logger? – Vladimir Sizikov Feb 18 '12 at 12:53
  • 6
    you can verify the mocked logger was called in case an exception was caught (failure scenario). that's espacially useful if you don't intend to rethrow it but want assert it's not silently ignored. – mantrid Feb 20 '12 at 18:46
23

Null Checks!

if( ${word_selection} != null ){
    ${cursor}
}

if( ${word_selection} == null ){
    ${cursor}
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Prashant Bhate
  • 10,130
  • 7
  • 42
  • 81
21

One of my beloved is foreach:

for (${iterable_type} ${iterable_element} : ${iterable}) {
    ${cursor}
}

And traceout, since I'm using it a lot for tracking:

System.out.println("${enclosing_type}.${enclosing_method}()");

I just thought about another one and have found it over the Internet some day, const:

private static final ${type} ${name} = new ${type} ${cursor};
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Artem Barger
  • 38,615
  • 9
  • 54
  • 80
20

A little tip on sysout -- I like to renamed it to "sop". Nothing else in the java libs starts with "sop" so you can quickly type "sop" and boom, it inserts.

Scott Stanchfield
  • 27,997
  • 9
  • 45
  • 60
  • 11
    By default, just typing *syso* will do the same as sysout. – MasterScrat Aug 10 '11 at 05:25
  • 9
    Beat ya by 25% with sop, though... ;) – Scott Stanchfield Nov 07 '11 at 23:32
  • 2
    Since Eclipse Mars there is a poor step backward on the shortcut **"syso" + Ctrl + Space**: it will list some classes that have the characters s, y, s and o in their name (due to new CamelCase finding). So, now you have to additionally chose **sysout** from the list and press Return. – bobbel Jul 30 '15 at 15:53
17

Throw an IllegalArgumentException with variable in current scope (illarg):

throw new IllegalArgumentException(${var});

Better

throw new IllegalArgumentException("Invalid ${var} " + ${var});  
javaguy
  • 4,076
  • 10
  • 30
  • 35
Jon
  • 55,763
  • 30
  • 120
  • 149
14

Nothing fancy for code production - but quite useful for code reviews

I have my template coderev low/med/high do the following

/**
 * Code Review: Low Importance
 * 
 *
 * TODO: Insert problem with code here 
 *
 */

And then in the Tasks view - will show me all of the code review comments I want to bring up during a meeting.

ist_lion
  • 2,977
  • 5
  • 38
  • 70
14

Some more templates here.

Includes:

  • Create a date object from a particular date
  • Create a new generic ArrayList
  • Logger setup
  • Log with specified level
  • Create a new generic HashMap
  • Iterate through a map, print the keys and values
  • Parse a time using SimpleDateFormat
  • Read a file line by line
  • Log and rethrow a caught exeption
  • Print execution time of a block of code
  • Create periodic Timer
  • Write a String to a file
berezovskyi
  • 1,983
  • 2
  • 18
  • 26
lucrussell
  • 4,754
  • 2
  • 30
  • 38
12

slf4j Logging

${imp:import(org.slf4j.Logger,org.slf4j.LoggerFactory)}

private static final Logger LOGGER = LoggerFactory
    .getLogger(${enclosing_type}.class);
Prashant Bhate
  • 10,130
  • 7
  • 42
  • 81
10

Post Java 7, a great way to set up loggers which need (or prefer) static references to the enclosing class is to use the newly introduced MethodHandles API to get the runtime class in a static context.

An example snippet for SLF4J is:

private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

Aside from being a simple snippet in any IDE, it is also less brittle if you refactor certain functionality into another class because you won't accidentally carry the class name with it.

RevanthKrishnaKumar V.
  • 1,779
  • 1
  • 19
  • 33
Timothy055
  • 56
  • 1
  • 4
10

Bean Property

private ${Type} ${property};

public ${Type} get${Property}() {
    return ${property};
}

public void set${Property}(${Type} ${property}) {
    ${propertyChangeSupport}.firePropertyChange("${property}", this.${property},     this.${property} = ${property});
}

PropertyChangeSupport

private PropertyChangeSupport ${propertyChangeSupport} = new PropertyChangeSupport(this);${:import(java.beans.PropertyChangeSupport,java.beans.PropertyChangeListener)}
public void addPropertyChangeListener(PropertyChangeListener listener) {
  ${propertyChangeSupport}.addPropertyChangeListener(listener);
}

public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
  ${propertyChangeSupport}.addPropertyChangeListener(propertyName, listener);
}

public void removePropertyChangeListener(PropertyChangeListener listener) {
  ${propertyChangeSupport}.removePropertyChangeListener(listener);
}

public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) {
  ${propertyChangeSupport}.removePropertyChangeListener(propertyName, listener);
}
qualidafial
  • 6,034
  • 2
  • 24
  • 35
9

strf -> String.format("msg", args) pretty simple but saves a bit of typing.

String.format("${cursor}",)
RevanthKrishnaKumar V.
  • 1,779
  • 1
  • 19
  • 33
pjp
  • 15,286
  • 3
  • 31
  • 55
  • 6
    I use `String.format("${string}",${objects})` because Eclipse allows me to tab between my string and my list of objects. – Duncan Jones Feb 13 '12 at 09:22
  • I use this version: `String.format(${word_selection}${},)${cursor}`, first select a string then use 'sf' on it. Add the %s and so on... – Christophe Roussy Oct 28 '14 at 16:25
9

When testing around with code I sometimes missed out on deleting some syso s. So I made myself a template called syt.

System.out.println(${word_selection}${});//${todo}:remove${cursor}

Before I compile I always check my TODOs and will never forget to delete a System.out again.

Calon
  • 3,986
  • 1
  • 16
  • 29
9

Invoke code on the GUI thread

I bind the following template to the shortcut slater to quickly dispatch code on the GUI thread.

${:import(javax.swing.SwingUtilities)}
SwingUtilities.invokeLater(new Runnable() {      
      @Override
      public void run() {
        ${cursor}
      }
    });
Duncan Jones
  • 59,308
  • 24
  • 169
  • 227
8

Get an SWT color from current display:

Display.getCurrent().getSystemColor(SWT.COLOR_${cursor})

Suround with syncexec

PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable(){
    public void run(){
        ${line_selection}${cursor}
    }
});

Use the singleton design pattern:

/**
 * The shared instance.
 */
private static ${enclosing_type} instance = new ${enclosing_type}();

/**
 * Private constructor.
 */
private ${enclosing_type}() {
    super();
}

/**
 * Returns this shared instance.
 *
 * @returns The shared instance
 */
public static ${enclosing_type} getInstance() {
    return instance;
}
Daniel Schneller
  • 13,020
  • 5
  • 40
  • 69
Manuel Selva
  • 16,987
  • 21
  • 76
  • 127
  • 3
    Just a quick note - According the Maestro known as Joshua Bloch using an Enum should be the preferred method for creating singletons in Java. – Pablojim Jul 02 '09 at 18:51
  • Hi Pablojim, Since I posted this template I start reading Effective Java and I changed my singletons implementations to enum. Nevertheless I didn't find a way to have the template generating the enum and thus modifying the class declaration. Have you got this template ? Thanks Manu – Manuel Selva Jul 03 '09 at 06:43
  • FYI: Here's the enum singleton pattern http://electrotek.wordpress.com/2008/08/06/singleton-in-java-the-proper-way/. I don't particulary like it but then I don't have many singletons. It's easy to turn this into a Java template. – pjp Jul 03 '09 at 09:44
  • 1
    For the enum approach, I hope all your singletons make sense as Comparable, Serializable objects, because a lot of Singletons don't (and he wonders why this "...approach has yet to be widely adopted" - because comparability and serialization don't make sense for some singleton classes!) – MetroidFan2002 Jun 12 '11 at 06:04
  • Serializable? Yes. Consider serialization of an Object with a reference to your Singleton. If it is not Serializable, then you might encounter a NPE. If it is (and you don't add methods to overwrite the default de-serialization), then you might get an other instance of your "Singleton". – Johannes Kuhn Aug 24 '12 at 21:45
8

And an equalsbuilder, hashcodebuilder adaptation:

${:import(org.apache.commons.lang.builder.EqualsBuilder,org.apache.commons.lang.builder.HashCodeBuilder)}
@Override
public boolean equals(Object obj) {
    return EqualsBuilder.reflectionEquals(this, obj);
}

@Override
public int hashCode() {
    return HashCodeBuilder.reflectionHashCode(this);
}
Jon
  • 55,763
  • 30
  • 120
  • 149
8

The template for the logger declaration is great.

I also create linfo, ldebug, lwarn, lerror for the log levels that I use more often.

lerror:

logger.error(${word_selection}${});${cursor}
fgui
  • 1,476
  • 1
  • 13
  • 14
8

Insert test methods should-given-when-then

I saw a similar version to this one recently while pair programming with a very good developer and friend, and I think it could be a nice addition to this list.

This template will create a new test method on a class, following the Given - When - Then approach from the behavior-driven development (BDD) paradigm on the comments, as a guide for structuring the code. It will start the method name with "should" and let you replace the rest of the dummy method name "CheckThisAndThat" with the best possible description of the test method responsibility. After filling the name, TAB will take you straight to the // Given section, so you can start typing your preconditions.

I have it mapped to the three letters "tst", with description "Test methods should-given-when-then" ;)

I hope you find it as useful as I did when I saw it:

@Test
public void should${CheckThisAndThat}() {
    Assert.fail("Not yet implemented");
    // Given
    ${cursor}

    // When


    // Then

}${:import(org.junit.Test, org.junit.Assert)}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
MacLuq
  • 141
  • 3
  • 6
  • I like that template. I added a "throws Exception" to ease the testing comfort some more. – Torsten Oct 24 '14 at 07:58
  • I like the BDD paradigm. Very nice template for that. And just a note: your very-good-developer-and-friend is gone! – bobbel Jul 30 '15 at 15:58
8

Create everything for an event

Since events are kinda a pain to create in Java--all those interfaces, methods, and stuff to write just for 1 event--I made a simple template to create everything needed for 1 event.

${:import(java.util.List, java.util.LinkedList, java.util.EventListener, java.util.EventObject)}

private final List<${eventname}Listener> ${eventname}Listeners = new LinkedList<${eventname}Listener>();

public final void add${eventname}Listener(${eventname}Listener listener)
{
    synchronized(${eventname}Listeners) {
        ${eventname}Listeners.add(listener);
    }
}

public final void remove${eventname}Listener(${eventname}Listener listener)
{
    synchronized(${eventname}Listeners) {
        ${eventname}Listeners.remove(listener);
    }
}

private void raise${eventname}Event(${eventname}Args args)
{
    synchronized(${eventname}Listeners) {
        for(${eventname}Listener listener : ${eventname}Listeners)
            listener.on${eventname}(args);
    }
}

public interface ${eventname}Listener extends EventListener
{
    public void on${eventname}(${eventname}Args args);
}

public class ${eventname}Args extends EventObject
{
    public ${eventname}Args(Object source${cursor})
    {
        super(source);
    }
}

If you have events that share a single EventObject, just delete the customized one inserted by the template and change the appropriate parts of raise___() and on____().

I had written a nice, little, elegant eventing mechanism using a generic interface and generic class, but it wouldn't work due to the way Java handles generics. =(

Edit: 1) I ran into the issue where threads were adding/removing listeners while an event was taking place. The List can't be modified while in use, so I added synchronized blocks where the list of listeners is being accessed or used, locking on the list itself.

Benny Jobigan
  • 4,600
  • 1
  • 28
  • 40
  • Sending events while being in a lock (synchronized or otherwise) is a deadlock waiting to happen. In this case it would be better to copy the listeners while in a synchronized block and iterating the new list. – ssindelar Mar 14 '15 at 05:58
  • Use a [ConcurrentLinkedQueue](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html). It does not require locking, because it has a weakly consistent iterator, which never throws a ConcurrentModificationException. – Stefan Dollase Dec 25 '15 at 14:13
7

Here is a constructor for non-instantiable classes:

// Suppress default constructor for noninstantiability
@SuppressWarnings("unused")
private ${enclosing_type}() {
    throw new AssertionError();
}

This one is for custom exceptions:

/**
 * ${cursor}TODO Auto-generated Exception
 */
public class ${Name}Exception extends Exception {
    /**
     * TODO Auto-generated Default Serial Version UID
     */
    private static final long serialVersionUID = 1L;    

    /**
     * @see Exception#Exception()
     */
    public ${Name}Exception() {
        super();
    }

    /**
     * @see Exception#Exception(String) 
     */
    public ${Name}Exception(String message) {
        super(message);         
    }

    /**
     * @see Exception#Exception(Throwable)
     */
    public ${Name}Exception(Throwable cause) {
        super(cause);           
    }

    /**
     * @see Exception#Exception(String, Throwable)
     */
    public ${Name}Exception(String message, Throwable cause) {
        super(message, cause);
    }
}
David M. Coe
  • 279
  • 1
  • 6
  • 14
7

Spring Injection

I know this is sort of late to the game, but here is one I use for Spring Injection in a class:

${:import(org.springframework.beans.factory.annotation.Autowired)}
private ${class_to_inject} ${var_name};

@Autowired
public void set${class_to_inject}(${class_to_inject} ${var_name}) {
  this.${var_name} = ${var_name};
}

public ${class_to_inject} get${class_to_inject}() {
  return this.${var_name};
}
Mike Clark
  • 11,179
  • 6
  • 36
  • 42
5

I like a generated class comment like this:

/**
 * I... 
 * 
 * $Id$
 */

The "I..." immediately encourages the developer to describe what the class does. I does seem to improve the problem of undocumented classes.

And of course the $Id$ is a useful CVS keyword.

skaffman
  • 381,978
  • 94
  • 789
  • 754
5

I've had a lot of use of these snippets, looking for null values and empty strings.

I use the "argument test"-templates as the first code in my methods to check received arguments.

testNullArgument

if (${varName} == null) {
    throw new NullPointerException(
        "Illegal argument. The argument cannot be null: ${varName}");
}

You may want to change the exception message to fit your company's or project's standard. However, I do recommend having some message that includes the name of the offending argument. Otherwise the caller of your method will have to look in the code to understand what went wrong. (A NullPointerException with no message produces an exception with the fairly nonsensical message "null").

testNullOrEmptyStringArgument

if (${varName} == null) {
    throw new NullPointerException(
        "Illegal argument. The argument cannot be null: ${varName}");
}
${varName} = ${varName}.trim();
if (${varName}.isEmpty()) {
    throw new IllegalArgumentException(
        "Illegal argument. The argument cannot be an empty string: ${varName}");
}

You can also reuse the null checking template from above and implement this snippet to only check for empty strings. You would then use those two templates to produce the above code.

The above template, however, has the problem that if the in argument is final you will have to amend the produced code some (the ${varName} = ${varName}.trim() will fail).

If you use a lot of final arguments and want to check for empty strings but doesn't have to trim them as part of your code, you could go with this instead:

if (${varName} == null) {
    throw new NullPointerException(
        "Illegal argument. The argument cannot be null: ${varName}");
}
if (${varName}.trim().isEmpty()) {
    throw new IllegalArgumentException(
        "Illegal argument. The argument cannot be an empty string: ${varName}");
}

testNullFieldState

I also created some snippets for checking variables that is not sent as arguments (the big difference is the exception type, now being an IllegalStateException instead).

if (${varName} == null) {
    throw new IllegalStateException(
        "Illegal state. The variable or class field cannot be null: ${varName}");
}

testNullOrEmptyStringFieldState

if (${varName} == null) {
    throw new IllegalStateException(
        "Illegal state. The variable or class field cannot be null: ${varName}");
}
${varName} = ${varName}.trim();
if (${varName}.isEmpty()) {
    throw new IllegalStateException(
        "Illegal state. The variable or class field " +
            "cannot be an empty string: ${varName}");
}

testArgument

This is a general template for testing a variable. It took me a few years to really learn to appreciate this one, now I use it a lot (in combination with the above templates of course!)

if (!(${varName} ${testExpression})) {
    throw new IllegalArgumentException(
        "Illegal argument. The argument ${varName} (" + ${varName} + ") " +
        "did not pass the test: ${varName} ${testExpression}");
}

You enter a variable name or a condition that returns a value, followed by an operand ("==", "<", ">" etc) and another value or variable and if the test fails the resulting code will throw an IllegalArgumentException.

The reason for the slightly complicated if clause, with the whole expression wrapped in a "!()" is to make it possible to reuse the test condition in the exception message.

Perhaps it will confuse a colleague, but only if they have to look at the code, which they might not have to if you throw these kind of exceptions...

Here's an example with arrays:

public void copy(String[] from, String[] to) {
    if (!(from.length == to.length)) {
        throw new IllegalArgumentException(
                "Illegal argument. The argument from.length (" +
                            from.length + ") " +
                "did not pass the test: from.length == to.length");
    }
}

You get this result by calling up the template, typing "from.length" [TAB] "== to.length".

The result is way funnier than an "ArrayIndexOutOfBoundsException" or similar and may actually give your users a chance to figure out the problem.

Enjoy!

Erk
  • 881
  • 12
  • 8
4

I use this for MessageFormat (using Java 1.4). That way I am sure that I have no concatenations that are hard to extract when doing internationalization

i18n

String msg = "${message}";
Object[] params = {${params}};
MessageFormat.format(msg, params);

Also for logging:

log

if(logger.isDebugEnabled()){
  String msg = "${message}"; //NLS-1
  Object[] params = {${params}};
  logger.debug(MessageFormat.format(msg, params));
}
Mario Ortegón
  • 17,860
  • 17
  • 67
  • 79
4

My favorite few are...

1: Javadoc, to insert doc about the method being a Spring object injection method.

 Method to set the <code>I${enclosing_type}</code> implementation that this class will use.
* 
* @param ${enclosing_method_arguments}<code>I${enclosing_type}</code> instance 

2: Debug window, to create a FileOutputStream and write the buffer's content's to a file. Used for when you want to compare a buffer with a past run (using BeyondCompare), or if you can't view the contents of a buffer (via inspect) because its too large...

java.io.FileOutputStream fos = new java.io.FileOutputStream( new java.io.File("c:\\x.x"));
fos.write(buffer.toString().getBytes());
fos.flush();
fos.close();
jeff porter
  • 6,196
  • 13
  • 59
  • 112
4
  • public int hashCode()
  • public boolean equals(Object)

Using explicit tests rather than reflection which is slower and might fail under a Security Manager (EqualsBuilder javadoc).

The template contains 20 members. You can move through them with TAB. Once finished, the remaining calls to apppend() have to be removed.

${:import(org.apache.commons.lang.builder.HashCodeBuilder, org.apache.commons.lang.builder.EqualsBuilder)}
@Override
public int hashCode() {
    return new HashCodeBuilder()
        .append(${field1:field})
        .append(${field2:field})
        .append(${field3:field})
        .append(${field4:field})
        .append(${field5:field})
        .append(${field6:field})
        .append(${field7:field})
        .append(${field8:field})
        .append(${field9:field})
        .append(${field10:field})
        .append(${field11:field})
        .append(${field12:field})
        .append(${field13:field})
        .append(${field14:field})
        .append(${field15:field})
        .append(${field16:field})
        .append(${field17:field})
        .append(${field18:field})
        .append(${field19:field})
        .append(${field20:field})
        .toHashCode();
}

@Override
public boolean equals(Object obj) {
    if (obj == null) {
        return false;
    }
    if (obj == this) {
        return true;
    }
    if (obj.getClass() != getClass()) {
        return false;
    }
    ${enclosing_type} rhs = (${enclosing_type}) obj;
    return new EqualsBuilder()
            .append(${field1}, rhs.${field1})
            .append(${field2}, rhs.${field2})
            .append(${field3}, rhs.${field3})
            .append(${field4}, rhs.${field4})
            .append(${field5}, rhs.${field5})
            .append(${field6}, rhs.${field6})
            .append(${field7}, rhs.${field7})
            .append(${field8}, rhs.${field8})
            .append(${field9}, rhs.${field9})
            .append(${field10}, rhs.${field10})
            .append(${field11}, rhs.${field11})
            .append(${field12}, rhs.${field12})
            .append(${field13}, rhs.${field13})
            .append(${field14}, rhs.${field14})
            .append(${field15}, rhs.${field15})
            .append(${field16}, rhs.${field16})
            .append(${field17}, rhs.${field17})
            .append(${field18}, rhs.${field18})
            .append(${field19}, rhs.${field19})
            .append(${field20}, rhs.${field20})${cursor}
            .isEquals();
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
gswierczynski
  • 2,433
  • 2
  • 19
  • 22
3

I use following templates for Android development:

Verbose (Logv)

Log.v(TAG, ${word_selection}${});${cursor}

Debug (Logd)

Log.d(TAG, ${word_selection}${});${cursor}

Info (Logi)

Log.i(TAG, ${word_selection}${});${cursor}

Warn (Logw)

Log.w(TAG, ${word_selection}${});${cursor}

Error (Loge)

Log.e(TAG, ${word_selection}${});${cursor}

Assert (Loga)

Log.a(TAG, ${word_selection}${});${cursor}

TAG is a Constant I define in every activity.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Terel
  • 3,669
  • 1
  • 23
  • 28
  • If you use `${type:newType(android.util.Log)}` instead of just `Log` then it will handle the import for you if you don't have it already. The `TAG` constant can be templatised as well: `private static final String TAG = "${enclosing_type}";` – Logan Pickup Nov 10 '13 at 23:05
3

Hamcrest Test with Static Imports

Here's a template to generate @Test methods with necessary hamcrest imports, if you want to use the new features of JUnit 4.8.2 (assertThat, is, hasItems, etc...)

@${testType:newType(org.junit.Test)}
public void ${testName}() throws Exception {
    // Arrange
    ${staticImport:importStatic('org.hamcrest.MatcherAssert.*','org.hamcrest.Matchers.*')}${cursor} 
    // Act

    // Assert

}

I already used it many times, when writing test.

What is Arrange-Act-Assert?

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
MartinL
  • 2,888
  • 4
  • 16
  • 19
3

With help of plugin: http://code.google.com/p/eclipse-log-param/

It's possible to add the following template:

logger.trace("${enclosing_method}. ${formatted_method_parameters});

And get result:

public static void saveUserPreferences(String userName, String[] preferences) {
    logger.trace("saveUserPreferences. userName: " + userName + " preferences: " + preferences);
}
Andrey Rodionov
  • 725
  • 5
  • 14
2

I just noticed @Duncan Jones already has this template, but adding the ${line_selection} and using Shift + Alt + Z is a useful tactic.

This is maybe only useful as a bit of a hacky fix to some bad design in a project I'm working on, but I have a lot of situations where some legacy code is modifying Swing components off the AWT thread and causing intermittent bugs, so to quickly patch these up I use:

${:import(javax.swing.SwingUtilities)}
// Ensure that any Swing components will be invoked only from the AWT thread
SwingUtilities.invokeLater(new Runnable() {

    @Override
    public void run() {
        ${line_selection}${cursor}
    }
});

So I can highlight the offending statements and use Shift + Alt + Z to surround with. I call this template swinvoke.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
dassimon
  • 141
  • 8
2

This takes a lot of the grunt work out of printing / logging local values. It automatically captures the variable name within a String. This saves a lot of typing and typo correction.

The template:

+ ", ${1:var}: " + ${1:var}

It has two pitfalls:

Although you are prompted to select a local / parameter / field, this does not include primitives :(

Prompting occurs most whenever the code is compiled with no errors. Often using this macro yields temporarily broken syntax, so some juggling is necessary to insert multiple variables. Nothing close to the convenience of not having typos in variable names.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Terry
  • 189
  • 3
  • 8
1

Here's a foreach that will work for iterating over a List<Stuff>. The optional content inside the loop is for finding an element in the list and return it.

for (${t:elemType(w)} elem: ${w:collection}) {
    if (elem.get.equals(${localVar})){
        return elem;
    }
}
return null;
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Manu de Hanoi
  • 273
  • 3
  • 14
1

Create a new JUnit test case from the selected word:

This requires a logger (called _logger: there is a very nice template for that in this thread as well).

I'm a big fan of this template, because it makes it very easy for me to create unimplemented test cases quickly the minute I think of them. They'll sit there failing on me as a reminder of the case I need to test.

${:import(org.junit.Test, org.junit.Assert)}
    @Test
    public void fooTest() throws Throwable {
        try {
            ${cursor}
            Assert.fail("Not Implemented");
        } catch (Throwable e) {
            _logger.error("Failed test", e);
            throw e;
        }
    }

To use it, type the name of the test case (say testSerializeObject), highlight the word, and hit Ctrl + Space (or whatever you've configured for code assist).

My favorite template for a test case is one that logs exceptions and then rethrows them since I like to see the exceptions in the console rather than in JUnit's exception viewer.

Should you prefer System.out in your tests over log files, you can always use something similar like:

${:import(org.junit.Test, org.junit.Assert)}
@Test
public void ${word_selection}() throws Exception {
    try {
        ${cursor}
        Assert.fail("Not Implemented");
    } catch (Exception e) {
        System.out.println("Failed test");
        e.printStackTrace();
        throw e;
    }
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Mason Bryant
  • 1,302
  • 14
  • 22
  • Sorry, but that template is flawed. Instead of System.out and printStackTrace get used to logging, generally. In a test method, don't have any such output methods at all. Also, avoid catching exceptions on the top level methods of unit test and let the unit test framework deal with them. – Bananeweizen Jan 19 '13 at 09:52
  • That was intentional: in my case it is easier to log directly to system out, but you'll note directly below that I mention the use of a logger if that is what you need. Also the catch and rethrow is so that the stack trace will print to the console, and not to the junit output pane. Why? Because the junit pane's line numbers are not clickable. – Mason Bryant Jan 19 '13 at 17:02
  • Also: I'm curious why you prefer no output in tests? Are you worried about spam when tests are run? Don't you want spam if your test is failing? – Mason Bryant Jan 19 '13 at 17:05
  • In my Eclipse installation, clicking a line of the Junit stack trace leads perfectly well to the source of it. Maybe my wording was bad, cause I also like many details for easy debugging, but absolutely not on sysout, as _everyone_ spams sysout. Those details have to go into assert statements or logger calls. When those tests run in Maven or on an integration server, I don't want people to have to go through the console log of the build to find all that output. – Bananeweizen Jan 20 '13 at 07:24
  • Ok, fair point. :) I generally hate System.out too (I tend to make an exception for failing unit tests) but I suppose it can lead a project in the wrong direction. I've edited to explicitly call out the logging version of the template. I left in the system.out version as well because I still believe it is a valid choice for some situations. – Mason Bryant Jan 21 '13 at 00:35
1

Code Section

//--------------------------------------------------------------
//                       ${title}
//--------------------------------------------------------------
${cursor}

Use this template to make commenting sections of code easier. it's not very complex, but has saved me lots of time :)

coderatchet
  • 7,214
  • 15
  • 60
  • 109
1

EasyMock templates

Create Mock

${:importStatic(org.easymock.EasyMock.createMock)}
${type} ${name} = createMock(${type}.class);

Reset Mock

${:importStatic(org.easymock.EasyMock.reset)}
reset(${var});

Replay Mock

${:importStatic(org.easymock.EasyMock.replay)}
replay(${var});

Verify Mock

${:importStatic(org.easymock.EasyMock.verify)}
verify(${var});
Brent Worden
  • 9,586
  • 7
  • 50
  • 50
0

Inner listener class for SWT and plugin development:

${imports:import(org.eclipse.swt.widgets.Listener)}
private class ${className} implements Listener{

    @Override
    public void handleEvent(Event e) {
        final Widget w = e.widget;
    }
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
tekkavi
  • 894
  • 9
  • 19
0

list_methods - generates the methods for add, removing, counting, and contains for a list

public void add${listname}(${listtype} toAdd){
    get${listname}s().add(toAdd);
}

public void remove${listname}(${listtype} toRemove){
    get${listname}s().remove(toRemove);
}

public ${listtype} get${listname}(int index){
    return get${listname}s().get(index);
}

public int get${listname}Count(){
    return get${listname}s().size();
}

public boolean contains${listname}(${listtype} toFind){
    return get${listname}s().contains(toFind);
}

${cursor}

id - inserts the annotations, imports, field, and getter for simple JPA @Id

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

public Long getId(){
    return id;
}

${cursor}
${:import (javax.persistence.GenerationType,javax.persistence.GeneratedValue,javax.persistence.Id)}
0

I saw an answer for a template creating a basic test class, and here are some individual calls if you prefer this approach instead:

Create setUp method with @Before import

${:import(org.junit.Before)}
@Before
public final void setUp() {
  ${cursor}
}

Create new test method with @Test import

${:import(org.junit.Test)}
@Test
public final void test${newName} () {
${cursor}
}

I use the following for helping with JAXB conversions between types and DTOs:

Template for converting existing variable to return value type (works with parameter)

${return_type} ${name} = null;

if (${var} != null) {
    ${name} = new ${return_type}();
    ${cursor}
}
return ${name};
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Gaʀʀʏ
  • 3,952
  • 2
  • 34
  • 56
0

This prints an entire object (assumes you have already initiated a log4j LOGGER object):

  ${:import(org.codehaus.jackson.map.ObjectMapper)}
  // If check to avoid argument evaluation costs
  if (LOGGER.isDebugEnabled()) {
        try {
            LOGGER.debug("Object ${Object}: " + "\n"
                + new ObjectMapper().writeValueAsString(${Object}));
        } catch (JsonGenerationException e) {
            LOGGER.info(e.toString());
        } catch (JsonMappingException e) {
            LOGGER.info(e.toString());
        } catch (IOException e) {
            LOGGER.info(e.toString());
        }
  }
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Gautam
  • 79
  • 1
  • 3
0

A new JUnit test method:

 @${testType:newType(org.junit.Test)}
 public void ${testname}() throws Exception {
     ${staticImport:importStatic('org.junit.Assert.*')}${cursor}

     String expected = "" ;
     String actual = "" ;

     Assert.assertEquals(expected, actual);
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Burhan ARAS
  • 2,396
  • 22
  • 18
0

Vector to Array

${array_type}[] ${v:var(Vector)}Array = new ${array_type}[${v}.size()];
${v}.copyInto(${v}Array);
Community
  • 1
  • 1
aeracode
  • 1,304
  • 22
  • 26