Useful Eclipse Java Code Templates [closed]

2019-01-01 04:06发布

You can create various Java code templates in Eclipse via

Window > Preferences > Java > Editor > Templates

e.g.

sysout is expanded to:

System.out.println(${word_selection}${});${cursor}

You can activate this by typing sysout followed by CTRL+SPACE

What useful Java code templates do you currently use?
Include the name and description of it and why it's awesome.

There's an open bounty on this for an original/novel use of a template rather than a built-in existing feature.

  • Create Log4J logger
  • Get swt color from display
  • Syncexec - Eclipse Framework
  • Singleton Pattern/Enum Singleton Generation
  • Readfile
  • Const
  • Traceout
  • Format String
  • Comment Code Review
  • String format
  • Try Finally Lock
  • Message Format i18n and log
  • Equalsbuilder
  • Hashcodebuilder
  • Spring Object Injection
  • Create FileOutputStream

30条回答
刘海飞了
2楼-- · 2019-01-01 04:42

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

private static Log log = LogFactory.getLog(${enclosing_type}.class);
查看更多
牵手、夕阳
3楼-- · 2019-01-01 04:43

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

查看更多
情到深处是孤独
4楼-- · 2019-01-01 04:43

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}
      }
    });
查看更多
千与千寻千般痛.
5楼-- · 2019-01-01 04:44

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

String.format("${cursor}",)
查看更多
骚的不知所云
6楼-- · 2019-01-01 04:46

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
查看更多
刘海飞了
7楼-- · 2019-01-01 04:46

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.

查看更多
登录 后发表回答