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


当前回答

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

SLF4J的一个示例片段是:

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

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

其他回答

我使用以下模板进行Android开发:

详细(日志)

Log.v(TAG, ${word_selection}${});${cursor}

调试(Logd)

Log.d(TAG, ${word_selection}${});${cursor}

(信息的人类学)

Log.i(TAG, ${word_selection}${});${cursor}

Warn (Logw)

Log.w(TAG, ${word_selection}${});${cursor}

错误(包厢)

Log.e(TAG, ${word_selection}${});${cursor}

Assert (Loga)

Log.a(TAG, ${word_selection}${});${cursor}

TAG是我在每个活动中定义的常量。

对于代码生产来说没什么特别的,但是对于代码审查来说非常有用

我有我的模板coderev low/med/high执行以下操作

/**
 * Code Review: Low Importance
 * 
 *
 * TODO: Insert problem with code here 
 *
 */

然后在Tasks视图中-将显示我想在会议期间提出的所有代码审查注释。

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

和一个equalsbuilder, hashcodebuilder适配:

${:import(org.apache.commons.lang.builder.EqualsBuilder,org.apache.commons.lang.builder.HashCodeBuilder)}
@Override
public boolean equals(Object obj) {
    return EqualsBuilder.reflectionEquals(this, obj);
}

@Override
public int hashCode() {
    return HashCodeBuilder.reflectionHashCode(this);
}

从当前显示中获取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;
}