Seeking useful Eclipse Java code templates

212,335

Solution 1

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

Solution 2

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
}

Solution 3

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

Solution 4

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

Solution 5

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

Share:
212,335
Jonathan Holloway
Author by

Jonathan Holloway

Consultant CTO and Architect with expertise in Java, Python, Ruby and Javascript http://www.jonathanholloway.co.uk/

Updated on July 08, 2022

Comments

  • Jonathan Holloway
    Jonathan Holloway almost 2 years

    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