您可以在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


当前回答

下面是一个非实例化类的构造函数:

// Suppress default constructor for noninstantiability
@SuppressWarnings("unused")
private ${enclosing_type}() {
    throw new AssertionError();
}

这个是针对自定义异常的:

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

其他回答

根据所选单词创建一个新的JUnit测试用例:

这需要一个记录器(称为_logger:在这个线程中也有一个非常好的模板)。

我是这个模板的忠实粉丝,因为它使我很容易在我想到它们的那一刻就快速地创建未实现的测试用例。他们会坐在那里不及格,提醒我要测试的案子。

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

要使用它,输入测试用例的名称(比如testSerializeObject),突出显示单词,并点击Ctrl + Space(或者您为代码辅助配置的任何东西)。

我最喜欢的测试用例模板是记录异常然后重新抛出它们的模板,因为我喜欢在控制台中而不是在JUnit的异常查看器中查看异常。

你喜欢系统吗?在你的测试日志文件中,你总是可以使用类似的东西:

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

EasyMock模板

创建模拟

${:importStatic(org.easymock.EasyMock.createMock)}
${type} ${name} = createMock(${type}.class);

重置模拟

${:importStatic(org.easymock.EasyMock.reset)}
reset(${var});

回放模拟

${:importStatic(org.easymock.EasyMock.replay)}
replay(${var});

验证模拟

${:importStatic(org.easymock.EasyMock.verify)}
verify(${var});

在Java 7之后,设置需要(或更喜欢)对外围类的静态引用的记录器的一个好方法是使用新引入的MethodHandles API在静态上下文中获取运行时类。

SLF4J的一个示例片段是:

private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

除了在任何IDE中都是一个简单的代码片段外,如果您将某些功能重构到另一个类中,它也不会那么脆弱,因为您不会意外地携带类名。

下面是一个foreach,用于迭代List<Stuff>。循环中的可选内容用于查找列表中的元素并返回它。

for (${t:elemType(w)} elem: ${w:collection}) {
    if (elem.get.equals(${localVar})){
        return elem;
    }
}
return null;

我知道我是在找死,但为了完成起见,我想分享这个:

单例生成模板的正确版本,克服了有缺陷的双重检查锁定设计(上面讨论过,其他地方也提到过)

单例创建模板: 命名为createsingleton

static enum Singleton {
    INSTANCE;

    private static final ${enclosing_type} singleton = new ${enclosing_type}();

    public ${enclosing_type} getSingleton() {
        return singleton;
    }
}
${cursor}

访问使用上述方法生成的单例对象:

单例引用模板: 命名这个getsingleton:

${type} ${newName} = ${type}.Singleton.INSTANCE.getSingleton();