首页 文章

有用的Eclipse Java代码模板[关闭]

提问于
浏览
493

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

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

例如

sysout 扩展为:

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

你可以输入 sysout 然后输入 CTRL+SPACE 来激活它

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

对于原始/新颖的模板使用而不是内置的现有功能,这是一个开放的赏金 .

  • 创建Log4J Logger

  • 从显示屏获取swt颜色

  • Syncexec - Eclipse Framework

  • Singleton Pattern / Enum Singleton Generation

  • Readfile

  • Const

  • Traceout

  • 格式字符串

  • 评论代码评论

  • 字符串格式

  • 尝试最后锁定

  • 消息格式i18n和日志

  • Equalsbuilder

  • Hashcodebuilder

  • Spring对象注入

  • 创建FileOutputStream

30 回答

  • 14

    更多模板here .

    包括:

    • 从特定日期创建日期对象

    • 创建一个新的通用ArrayList

    • Logger 设置

    • 以指定级别记录

    • 创建一个新的通用HashMap

    • 遍历 Map ,打印键和值

    • 使用SimpleDateFormat解析时间

    • 逐行读取文件

    • 记录并重新抛出捕获的exeption

    • 打印代码块的执行时间

    • 创建定期计时器

    • 将字符串写入文件

  • 25

    关于sysout的一点建议 - 我喜欢将其重命名为“sop” . java libs中没有任何其他内容以“sop”开头,因此您可以快速输入“sop”和boom,它会插入 .

  • 21

    和一个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);
    }
    
  • 407

    我知道我正在踢一个死的帖子,但是为了完成起见想分享这个:

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

    Singleton Creation Template: 将此命名为 createsingleton

    static enum Singleton {
        INSTANCE;
    
        private static final ${enclosing_type} singleton = new ${enclosing_type}();
    
        public ${enclosing_type} getSingleton() {
            return singleton;
        }
    }
    ${cursor}
    

    要访问使用上面生成的单例:

    Singleton reference Template: 将此名称命名为 getsingleton

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

    Logger 声明的模板很棒 .

    我还为我经常使用的日志级别创建了linfo,ldebug,lwarn,lerror .

    lerror:

    logger.error(${word_selection}${});${cursor}
    
  • 47

    在Java 7之后,设置需要(或更喜欢)对封闭类的静态引用的 Logger 的一种好方法是使用新引入的MethodHandles API在静态上下文中获取运行时类 .

    SLF4J的示例代码段是:

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

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

  • 7

    Spring Injection

    我知道这对游戏来说有点晚了,但这里有一个我在一个类中用于Spring Injection的方法:

    ${:import(org.springframework.beans.factory.annotation.Autowired)}
    private ${class_to_inject} ${var_name};
    
    @Autowired
    public void set${class_to_inject}(${class_to_inject} ${var_name}) {
      this.${var_name} = ${var_name};
    }
    
    public ${class_to_inject} get${class_to_inject}() {
      return this.${var_name};
    }
    
  • 5

    slf4j记录

    ${imp:import(org.slf4j.Logger,org.slf4j.LoggerFactory)}
    
    private static final Logger LOGGER = LoggerFactory
        .getLogger(${enclosing_type}.class);
    
  • 4

    插入测试方法应该在当时给出

    我最近看到了与这个版本类似的版本,而且与一位非常优秀的开发人员和朋友进行了对编程,我认为这可能是这个列表的一个很好的补充 .

    此模板将在类上创建一个新的测试方法,遵循注释中behavior-driven development(BDD)范例的Given - When - Then approach作为构造代码的指南 . 它将使用"should"启动方法名称,并允许您使用测试方法职责的最佳描述替换虚拟方法名称"CheckThisAndThat"的其余部分 . 填写完姓名后,TAB会直接转到 // Given section ,这样您就可以开始输入前提条件了 .

    我把它映射到三个字母“tst”,描述“测试方法应当给予时 - 然后”;)

    我希望你发现它和我看到它时一样有用:

    @Test
    public void should${CheckThisAndThat}() {
        Assert.fail("Not yet implemented");
        // Given
        ${cursor}
    
        // When
    
    
        // Then
    
    }${:import(org.junit.Test, org.junit.Assert)}
    
  • 9

    为事件创建所有内容

    由于在Java中创建事件有点痛苦 - 所有这些接口,方法和仅为1个事件编写的东西 - 我创建了一个简单的模板来创建1个事件所需的所有内容 .

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

    如果您有共享单个 EventObject 的事件,只需删除模板插入的自定义事件,然后更改 raise___()on____() 的相应部分 .

    我使用通用接口和泛型类编写了一个漂亮,小巧,优雅的事件机制,但由于Java处理泛型的方式,它不起作用 . =(

    Edit :1)我遇到了线程在事件发生时添加/删除侦听器的问题 . List 在使用时无法修改,因此我添加了 synchronized 块,其中正在访问或使用侦听器列表,锁定列表本身 .

  • 20

    在使用代码进行测试时,我有时会错过删除一些 syso . 所以我自己制作了一个名为 syt 的模板 .

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

    在编译之前,我总是检查我的TODO,并且永远不会忘记再次删除System.out .

  • 31

    对于 log ,添加成员变量是一个有用的小小调 .

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

    我已经大量使用这些片段,寻找 null 值并清空字符串 .

    我使用“参数测试”-templates作为我的方法中的第一个检查接收参数的代码 .

    testNullArgument

    if (${varName} == null) {
        throw new NullPointerException(
            "Illegal argument. The argument cannot be null: ${varName}");
    }
    

    您可能希望更改异常消息以适合您的公司's or project'标准 . 但是,我建议使用包含违规参数名称的消息 . 否则,您的方法的调用者将不得不查看代码以了解出错的地方 . (没有消息的 NullPointerException 会产生一个带有相当荒谬的消息"null"的异常) .

    testNullOrEmptyStringArgument

    if (${varName} == null) {
        throw new NullPointerException(
            "Illegal argument. The argument cannot be null: ${varName}");
    }
    ${varName} = ${varName}.trim();
    if (${varName}.isEmpty()) {
        throw new IllegalArgumentException(
            "Illegal argument. The argument cannot be an empty string: ${varName}");
    }
    

    您还可以重用上面的空检查模板,并实现此片段以仅检查空字符串 . 然后,您将使用这两个模板来生成上述代码 .

    但是,上面的模板存在的问题是,如果in参数是final,则必须修改生成的代码( ${varName} = ${varName}.trim() 将失败) .

    如果您使用了很多最终参数并且想要检查空字符串但不必将它们作为代码的一部分进行修剪,那么您可以改为:

    if (${varName} == null) {
        throw new NullPointerException(
            "Illegal argument. The argument cannot be null: ${varName}");
    }
    if (${varName}.trim().isEmpty()) {
        throw new IllegalArgumentException(
            "Illegal argument. The argument cannot be an empty string: ${varName}");
    }
    

    testNullFieldState

    我还创建了一些片段来检查未作为参数发送的变量(最大的区别是异常类型,现在是 IllegalStateException ) .

    if (${varName} == null) {
        throw new IllegalStateException(
            "Illegal state. The variable or class field cannot be null: ${varName}");
    }
    

    testNullOrEmptyStringFieldState

    if (${varName} == null) {
        throw new IllegalStateException(
            "Illegal state. The variable or class field cannot be null: ${varName}");
    }
    ${varName} = ${varName}.trim();
    if (${varName}.isEmpty()) {
        throw new IllegalStateException(
            "Illegal state. The variable or class field " +
                "cannot be an empty string: ${varName}");
    }
    

    testArgument

    这是测试变量的通用模板 . 我花了几年才真正学会欣赏这个,现在我经常使用它(当然结合上面的模板!)

    if (!(${varName} ${testExpression})) {
        throw new IllegalArgumentException(
            "Illegal argument. The argument ${varName} (" + ${varName} + ") " +
            "did not pass the test: ${varName} ${testExpression}");
    }
    

    输入变量名称或返回值的条件,后跟操作数(“==”,“<”,“>”等)和另一个值或变量,如果测试失败,结果代码将抛出IllegalArgumentException .

    稍微复杂的if子句,整个表达式包含在“!()”中的原因是为了能够在异常消息中重用测试条件 .

    也许它会让同事感到困惑,但前提是他们必须查看代码,如果你抛出这些异常,他们可能不需要这些代码......

    这是一个数组的例子:

    public void copy(String[] from, String[] to) {
        if (!(from.length == to.length)) {
            throw new IllegalArgumentException(
                    "Illegal argument. The argument from.length (" +
                                from.length + ") " +
                    "did not pass the test: from.length == to.length");
        }
    }
    

    通过调用模板,输入“from.length”[TAB]“== to.length”得到这个结果 .

    结果比“ArrayIndexOutOfBoundsException”或类似方法更有趣,实际上可能会让您的用户有机会找出问题所在 .

    请享用!

  • 8

    这里还有一些额外的模板:Link I - Link II

    我喜欢这一个:

    readfile

    ${:import(java.io.BufferedReader,  
               java.io.FileNotFoundException,  
               java.io.FileReader,  
               java.io.IOException)}  
     BufferedReader in = null;  
     try {  
        in = new BufferedReader(new FileReader(${fileName}));  
        String line;  
        while ((line = in.readLine()) != null) {  
           ${process}  
        }  
     }  
     catch (FileNotFoundException e) {  
        logger.error(e) ;  
     }  
     catch (IOException e) {  
        logger.error(e) ;  
     } finally {  
        if(in != null) in.close();  
     }  
     ${cursor}
    

    UPDATE :此模板的Java 7版本是:

    ${:import(java.nio.file.Files,
              java.nio.file.Paths,
              java.nio.charset.Charset,
              java.io.IOException,
              java.io.BufferedReader)}
    try (BufferedReader in = Files.newBufferedReader(Paths.get(${fileName:var(String)}),
                                                     Charset.forName("UTF-8"))) {
        String line = null;
        while ((line = in.readLine()) != null) {
            ${cursor}
        }
    } catch (IOException e) {
        // ${todo}: handle exception
    }
    
  • 17

    使用当前范围(illarg)中的变量抛出IllegalArgumentException:

    throw new IllegalArgumentException(${var});
    

    更好

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

    这是非实例化类的构造函数:

    // 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);
        }
    }
    
  • 11

    格式化字符串

    MessageFormat - 使用MessageFormat包围选择 .

    ${:import(java.text.MessageFormat)} 
     MessageFormat.format(${word_selection}, ${cursor})
    

    这允许我将光标移动到一个字符串,将选择扩展到整个字符串(Shift-Alt-Up),然后按两次Ctrl-Space .

    锁定选择

    锁定 - 使用try finally锁定所选行 . 假设存在锁变量 .

    ${lock}.acquire();
    try {
        ${line_selection}
        ${cursor}
    } finally {
        ${lock}.release();
    }
    

    NB ${line_selection} 模板显示在 Surround With 菜单中(Alt-Shift-Z) .

  • 7

    strf -> String.format("msg", args) 非常简单,但节省了一点打字 .

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

    使用Mockito创建一个模拟(在“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});
    

    验证模拟方法永远不会被调用:

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

    使用Google 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
    
  • 8

    附加代码片段以迭代 Map.entrySet()

    模板:

    ${:import(java.util.Map.Entry)}
    for (Entry<${keyType:argType(map, 0)}, ${valueType:argType(map, 1)}> ${entry} : ${map:var(java.util.Map)}.entrySet())
    {
        ${keyType} ${key} = ${entry}.getKey();
        ${valueType} ${value} = ${entry}.getValue();
        ${cursor}
    }
    

    生成的代码:

    for (Entry<String, String> entry : properties.entrySet())
    {
        String key = entry.getKey();
        String value = entry.getValue();
        |
    }
    

    Screenshot

  • 25

    如果需要,以下代码模板将创建 Logger 并创建正确的导入 .

    SLF4J

    ${:import(org.slf4j.Logger,org.slf4j.LoggerFactory)}
    private static final Logger LOG = LoggerFactory.getLogger(${enclosing_type}.class);
    

    Log4J 2

    ${:import(org.apache.logging.log4j.LogManager,org.apache.logging.log4j.Logger)} 
    private static final Logger LOG = LogManager.getLogger(${enclosing_type}.class);
    

    Log4J

    ${:import(org.apache.log4j.Logger)}
    private static final Logger LOG = Logger.getLogger(${enclosing_type}.class);
    

    Source .

    JUL

    ${:import(java.util.logging.Logger)}
    private static final Logger LOG = Logger.getLogger(${enclosing_type}.class.getName());
    
  • 9

    我心爱的人之一是 foreach

    for (${iterable_type} ${iterable_element} : ${iterable}) {
        ${cursor}
    }
    

    并且 traceout ,因为我正在使用它进行跟踪:

    System.out.println("${enclosing_type}.${enclosing_method}()");
    

    我只想到另一个,并且有一天在互联网上找到它, const

    private static final ${type} ${name} = new ${type} ${cursor};
    
  • 4

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

    没有什么花哨的代码生成 - 但对代码审查非常有用

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

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

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

  • 14

    Invoke code on the GUI thread

    我将以下模板绑定到快捷方式 slater ,以便在GUI线程上快速调度代码 .

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

    Bean Property

    private ${Type} ${property};
    
    public ${Type} get${Property}() {
        return ${property};
    }
    
    public void set${Property}(${Type} ${property}) {
        ${propertyChangeSupport}.firePropertyChange("${property}", this.${property},     this.${property} = ${property});
    }
    

    PropertyChangeSupport

    private PropertyChangeSupport ${propertyChangeSupport} = new PropertyChangeSupport(this);${:import(java.beans.PropertyChangeSupport,java.beans.PropertyChangeListener)}
    public void addPropertyChangeListener(PropertyChangeListener listener) {
      ${propertyChangeSupport}.addPropertyChangeListener(listener);
    }
    
    public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
      ${propertyChangeSupport}.addPropertyChangeListener(propertyName, listener);
    }
    
    public void removePropertyChangeListener(PropertyChangeListener listener) {
      ${propertyChangeSupport}.removePropertyChangeListener(listener);
    }
    
    public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) {
      ${propertyChangeSupport}.removePropertyChangeListener(propertyName, listener);
    }
    
  • 23

    我将它用于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));
    }
    
  • 10

    我最喜欢的几个是......

    1:Javadoc,插入关于该方法的文档是一个Spring对象注入方法 .

    Method to set the <code>I${enclosing_type}</code> implementation that this class will use.
    * 
    * @param ${enclosing_method_arguments}<code>I${enclosing_type}</code> instance
    

    2:调试窗口,创建FileOutputStream并将缓冲区的内容写入文件 . 用于何时想要将缓冲区与过去运行进行比较(使用BeyondCompare),或者如果无法查看缓冲区的内容(通过检查),因为它太大了......

    java.io.FileOutputStream fos = new java.io.FileOutputStream( new java.io.File("c:\\x.x"));
    fos.write(buffer.toString().getBytes());
    fos.flush();
    fos.close();
    
  • 24

    空检查!

    if( ${word_selection} != null ){
        ${cursor}
    }
    
    if( ${word_selection} == null ){
        ${cursor}
    }
    
  • 9

    我喜欢这样生成的类注释:

    /**
     * I... 
     * 
     * $Id$
     */
    

    “我...”立即鼓励开发人员描述该课程的作用 . 我似乎确实改善了无证件类的问题 .

    当然$ Id $是一个有用的CVS关键字 .

相关问题