score:427

Accepted answer

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());

score:0

vector to array

${array_type}[] ${v:var(vector)}array = new ${array_type}[${v}.size()];
${v}.copyinto(${v}array);

score: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;
    }
}

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

score: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};

score: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());
        }
  }

score: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);
}

score: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});

score: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;

score: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;
    }
}

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

score: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.

score: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.

score: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?

score: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);
}

score: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.

score: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));
}

score: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();

score: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();
}

score: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.

score: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!

score: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};
}

score: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);
    }
}

score: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;
}

score: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);
}

score: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}

score: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.

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

score:9

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

string.format("${cursor}",)

score: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}
      }
    });

score: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.

score: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);
}

score: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.

score:12

slf4j logging

${imp:import(org.slf4j.logger,org.slf4j.loggerfactory)}

private static final logger logger = loggerfactory
    .getlogger(${enclosing_type}.class);

score: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.

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

score:17

throw an illegalargumentexception with variable in current scope (illarg):

throw new illegalargumentexception(${var});

better

throw new illegalargumentexception("invalid ${var} " + ${var});  

score: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.

score: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};

score:23

null checks!

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

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

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

score:25

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

private static log log = logfactory.getlog(${enclosing_type}.class);

score: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();

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

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

score: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
}

Related Query

More Query from same tag