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


当前回答

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

其他回答

从当前显示中获取SWT颜色:

Display.getCurrent().getSystemColor(SWT.COLOR_${cursor})

周围都是syncexec

PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable(){
    public void run(){
        ${line_selection}${cursor}
    }
});

使用单例设计模式:

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

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

strf ->字符串。Format ("msg", args)非常简单,但节省了一些输入。

String.format("${cursor}",)

在GUI线程上调用代码

我将下面的模板绑定到快捷方式slater,以便在GUI线程上快速分派代码。

${:import(javax.swing.SwingUtilities)}
SwingUtilities.invokeLater(new Runnable() {      
      @Override
      public void run() {
        ${cursor}
      }
    });

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

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