views:

6038

answers:

18

You can create various Java code templates in Eclipse via the

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
+11  A: 

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

private static Log log = LogFactory.getLog(${enclosing_type}.class);
altCognito
+7  A: 

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

Just thought about another one, have found it over Internet some day const:

private static final ${type} ${name} = new ${type} ${cursor};
Artem Barger
foreach is available as a standard code assist in Eclipse, I don't see that your template does anything additional to the standard version
Rich Seller
Right, and sysout is very innovative template. The question was regarding, useful templates we are using.
Artem Barger
+45  A: 

Create Log4J logger:

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

It both creates the Logger with a proper category and imports it.

Source.

Robert Munteanu
Cool. I didn't know about the ${:import ...} thingy.
JesperE
Me neither, nice!
altCognito
Excellent, this was new info for me also.
Troggy
I think ${:import ...} only works in newer versions of Eclipse. I'm stuck with 3.2 and it doesn't work for me.
Adam Crume
wow that is really impressive
Yoely
Not in my version (3.5) either. Does anyone know which version it was introduced in?
finnw
It works fine for me in 3.5 .
Robert Munteanu
The import statement is great, nice.
rado
+4  A: 

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;
}
Manuel Selva
Daniel, thanks for your edit ;o)
Manuel Selva
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
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 ?ThanksManu
Manuel Selva
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
+9  A: 

Some additional templates here:

http://fahdshariff.blogspot.com/2008/11/eclipse-code-templates.html

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}
Jon
i think this is what a method is for :)
drscroogemcduck
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
+4  A: 

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.

PSU_Kardi
+2  A: 

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
+2  A: 

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
+3  A: 

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

String.format("${cursor}",)
pjp
+7  A: 

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
+7  A: 

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
+2  A: 

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
+1  A: 

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

throw new IllegalArgumentException(${var});
Jon
+2  A: 

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}
zesc
+2  A: 

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
+2  A: 

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 as createsingleton, and

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 ias getsingleton,

${type} ${newName} = ${type}.Singleton.INSTANCE.getSingleton();
questzen
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
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
+3  A: 

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
lrussell
A: 

When did you use "${word_selection}${}" What it means?

June