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


当前回答

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

其他回答

为一个事件创造一切

因为在Java中创建事件有点麻烦——所有这些接口、方法和东西都要为一个事件编写——我制作了一个简单的模板来创建一个事件所需的一切。

${:import(java.util.List, java.util.LinkedList, java.util.EventListener, java.util.EventObject)}

private final List<${eventname}Listener> ${eventname}Listeners = new LinkedList<${eventname}Listener>();

public final void add${eventname}Listener(${eventname}Listener listener)
{
    synchronized(${eventname}Listeners) {
        ${eventname}Listeners.add(listener);
    }
}

public final void remove${eventname}Listener(${eventname}Listener listener)
{
    synchronized(${eventname}Listeners) {
        ${eventname}Listeners.remove(listener);
    }
}

private void raise${eventname}Event(${eventname}Args args)
{
    synchronized(${eventname}Listeners) {
        for(${eventname}Listener listener : ${eventname}Listeners)
            listener.on${eventname}(args);
    }
}

public interface ${eventname}Listener extends EventListener
{
    public void on${eventname}(${eventname}Args args);
}

public class ${eventname}Args extends EventObject
{
    public ${eventname}Args(Object source${cursor})
    {
        super(source);
    }
}

如果您有共享单个eventtobject的事件,只需删除模板插入的自定义事件,并更改raise___()和____()上的适当部分。

我已经使用泛型接口和泛型类编写了一个漂亮、小巧、优雅的事件机制,但由于Java处理泛型的方式,它无法工作。=(

编辑: 1)我遇到了线程在事件发生时添加/删除侦听器的问题。List在使用时不能被修改,所以我在侦听器列表被访问或使用的地方添加了同步块,锁定在列表本身上。

使用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

对于log,在成员变量中添加一个有用的小调。

private static Log log = LogFactory.getLog(${enclosing_type}.class);

这省去了大量打印/记录本地值的繁琐工作。它自动捕获字符串中的变量名。这节省了大量的打字和错字改正。

模板:

+ ", ${1:var}: " + ${1:var}

它有两个陷阱:

尽管会提示您选择一个本地/参数/字段,但这并不包括原语:(

只要编译代码时没有错误,就会出现大多数提示。使用这个宏通常会导致语法暂时被破坏,因此需要使用一些杂耍来插入多个变量。没有什么比在变量名中没有错别字更方便的了。

我将此用于MessageFormat(使用Java 1.4)。通过这种方式,我可以确保在进行国际化时没有难以提取的连接

i18n

String msg = "${message}";
Object[] params = {${params}};
MessageFormat.format(msg, params);

同样用于日志:

log

if(logger.isDebugEnabled()){
  String msg = "${message}"; //NLS-1
  Object[] params = {${params}};
  logger.debug(MessageFormat.format(msg, params));
}