您可以在Eclipse中创建各种Java代码模板

窗口>首选项> Java >编辑器>模板

e.g.

Sysout扩展为:

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

您可以通过输入sysout加上CTRL+SPACE来激活它

您目前使用哪些有用的Java代码模板?包括它的名称和描述,以及为什么它很棒。

我正在寻找一个模板的原始/新颖的使用,而不是一个内置的现有功能。

创建Log4J日志记录器 从显示中获取swt颜色 Syncexec - Eclipse框架 单例模式/Enum单例生成 Readfile 常量 Traceout 格式字符串 注释代码审查 字符串格式 尝试最终锁定 消息格式i18n和log Equalsbuilder Hashcodebuilder Spring对象注入 创建FileOutputStream


当前回答

这将打印整个对象(假设你已经初始化了一个log4j LOGGER对象):

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

其他回答

使用Mockito创建一个mock(在“Java语句”上下文中):

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

在“Java类型成员”中:

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

模拟void方法抛出异常:

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

模拟一个void方法来做一些事情:

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

验证被模拟的方法被精确地调用一次:

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

验证mock方法从未被调用:

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

使用谷歌Guava的新链表(hashset和hashmap也类似):

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

我还使用了一个生成Test类的巨大模板。下面是一个简短的片段,每个感兴趣的人都应该定制:

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

在当前范围内抛出一个变量IllegalArgumentException (illarg):

throw new IllegalArgumentException(${var});

更好的

throw new IllegalArgumentException("Invalid ${var} " + ${var});  

在测试代码时,我有时会错过删除一些系统。所以我给自己做了一个名为syt的模板。

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

在我编译之前,我总是检查我的todo,永远不会忘记删除一个系统。出来。

插入测试方法时应给出

我最近在与一个非常优秀的开发人员和朋友结对编程时看到了一个类似的版本,我认为它可以成为这个列表的一个很好的补充。

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.

我把它映射到三个字母“tst”,描述为“测试方法应该在什么时候给出”;)

我希望你能像我看到它时一样觉得它很有用:

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

    // When


    // Then

}${:import(org.junit.Test, org.junit.Assert)}

我刚刚注意到@邓肯琼斯已经有这个模板,但添加${line_selection}和使用Shift + Alt + Z是一个有用的策略。

这可能只是我正在从事的项目中一些糟糕设计的一点hack fix,但我有很多情况下,一些遗留代码正在修改AWT线程之外的Swing组件,并导致间歇性错误,所以为了快速修补这些问题,我使用:

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

因此,我可以突出显示违规语句,并使用Shift + Alt + Z环绕。我把这个模板称为swinvoke。