代码之家  ›  专栏  ›  技术社区  ›  Jon

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

  •  498
  • Jon  · 技术社区  · 7 年前

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

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

    例如。

    sysout 扩展为:

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

    您可以通过键入 sysout 然后 CTRL+SPACE

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

    我正在寻找一个模板的原创/新颖的使用,而不是一个内置的现有功能。

    • 创建Log4J记录器
    • 从显示器获取swt颜色
    • Syncexec-Eclipse框架
    • Singleton模式/枚举Singleton生成
    • Readfile
    • Const
    • Traceout
    • 设置字符串格式
    • 注释代码审查
    • 字符串格式
    • Try Finally Lock
    • 消息格式i18n和日志
    • Equalsbuilder
    • 哈希代码生成器
    • Spring对象注入
    • 创建文件输出流
    46 回复  |  直到 7 年前
        1
  •  426
  •   D_Guidi    9 年前

    如果需要,以下代码模板将创建一个记录器并创建正确的导入。

    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());
    
        2
  •  49
  •   Jon    11 年前

    此处提供一些附加模板: Link I - Link II

    我喜欢这个:

    读取文件

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

    更新 :此模板的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
    }
    
        3
  •  33
  •   jamesh    15 年前

    设置字符串格式

    MessageFormat-用MessageFormat包围所选内容。

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

    这使我可以将光标移动到一个字符串,将所选内容扩展到整个字符串(Shift-Alt-Up),然后按两次Ctrl-Space。

    锁定所选内容

    lock-用try-filly锁定将选定的行包围起来。假设存在一个锁变量。

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

    NB ${line_selection} 模板显示在 环绕 菜单(Alt-Shift-Z)。

        4
  •  28
  •   questzen    13 年前

    我知道我在踢一个死帖子,但为了完成任务,我想分享一下:

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

    Singleton创建模板: 命名此 createsingleton

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


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

    Singleton参考模板: 命名此 getsingleton :

    ${type} ${newName} = ${type}.Singleton.INSTANCE.getSingleton();
    
        5
  •  28
  •   mmdemirbas    6 年前

    附加要迭代的代码段 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

        6
  •  25
  •   cgp    17 年前

    对于 log ,添加到成员变量中的一首有用的小曲。

    private static Log log = LogFactory.getLog(${enclosing_type}.class);
    
        7
  •  24
  •   mantrid    8 年前

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

    模仿一个空洞的方法来做某事:

    ${: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
  •  23
  •   Prashant Bhate    9 年前

    空支票!

    if( ${word_selection} != null ){
        ${cursor}
    }
    
    if( ${word_selection} == null ){
        ${cursor}
    }
    
        9
  •  21
  •   Artem Barger    9 年前

    我心爱的人之一是 前臂 :

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

    追踪 ,因为我经常使用它进行跟踪:

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

    我只是想了另一个,有一天在网上找到了, const :

    private static final ${type} ${name} = new ${type} ${cursor};
    
        10
  •  20
  •   Scott Stanchfield    17 年前

    关于sysout的一个小提示——我喜欢将其重命名为“sop”。javalibs中没有任何其他内容以“sop”开头,因此您可以快速键入“sop”并插入boom。

        11
  •  17
  •   javaguy    14 年前

    使用当前作用域中的变量引发IllegalArgumentException(illarg):

    throw new IllegalArgumentException(${var});
    

    较好的

    throw new IllegalArgumentException("Invalid ${var} " + ${var});  
    
        12
  •  14
  •   ist_lion    17 年前

    对代码生成来说没有什么特别的东西,但对代码评审非常有用

    我有我的模板代码rev-low/med/high,请执行以下操作

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

    然后在“任务”视图中,将显示我想在会议期间提出的所有代码评审意见。

        13
  •  14
  •   lrussell    9 年前

    更多模板 here

    包括:

    • 从特定日期创建日期对象
    • 创建新的通用ArrayList
    • 记录器设置
    • 使用指定级别记录
    • 创建新的通用HashMap
    • 遍历地图,打印键和值
    • 使用SimpleDateFormat分析时间
    • 逐行读取文件
    • 记录并重新抛出捕获的异常
    • 打印代码块的执行时间
    • 创建定期计时器
    • 将字符串写入文件
        14
  •  12
  •   Prashant Bhate    15 年前

    slf4j日志记录

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

    Bean属性

    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);
    }
    
        16
  •  10
  •   Timothy055    11 年前

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

    SLF4J的一个示例片段是:

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

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

        17
  •  9
  •   Duncan Jones    14 年前

    在GUI线程上调用代码

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

    ${:import(javax.swing.SwingUtilities)}
    SwingUtilities.invokeLater(new Runnable() {      
          @Override
          public void run() {
            ${cursor}
          }
        });
    
        18
  •  9
  •   Calon    12 年前

    在测试代码时,我有时会错过删除一些 syso s.所以我给自己做了一个模板,名为 syt

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

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

        19
  •  9
  •   Daniel    11 年前

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

    String.format("${cursor}",)
    
        20
  •  8
  •   Manuel Selva    17 年前

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

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

    使用syncexec Suround

    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;
    }
    
        21
  •  8
  •   Jon    17 年前

    以及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);
    }
    
        22
  •  8
  •   fgui    17 年前

    记录器声明的模板非常好。

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

    lerror:

    logger.error(${word_selection}${});${cursor}
    
        23
  •  8
  •   Benny Jobigan    14 年前

    创建事件的所有内容

    由于在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);
        }
    }
    

    如果您的活动共享一个 EventObject ,只需删除模板插入的自定义部分,然后更改 raise___() on____()

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

    编辑 : 1) 在事件发生时,我遇到了线程添加/删除侦听器的问题。这个 List 使用时无法修改,所以我添加了 synchronized 阻止正在访问或使用侦听器列表的位置,锁定列表本身。

        24
  •  8
  •   MacLuq    9 年前

    插入测试方法应在

    我最近在与一位非常好的开发人员和朋友配对编程时看到了一个与此类似的版本,我认为它可能是这个列表中的一个很好的补充。

    此模板将在类上创建一个新的测试方法,遵循 Given - When - Then approach 来自 behavior-driven development (BDD)关于注释的范式,作为构建代码的指南。它将以“应该”开头方法名称,并让您用测试方法责任的最佳描述替换伪方法名称“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)}
    
        25
  •  7
  •   Mike Clark    15 年前

    弹簧注射

    我知道这有点晚了,但这里是我在课堂上用于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};
    }
    
        26
  •  7
  •   David M. Coe    14 年前

    以下是不可实例化类的构造函数:

    // 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);
        }
    }
    
        27
  •  5
  •   skaffman    17 年前

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

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

    “I…”立即鼓励开发人员描述类的作用。我似乎确实改善了无证类的问题。

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

        28
  •  5
  •   Erk    12 年前

    我经常使用这些片段 null 值和空字符串。

    我使用“参数测试”模板作为方法中的第一个代码来检查收到的参数。

    testNullArgument

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

    您可能需要更改异常消息以符合公司或项目的标准。然而,我确实建议有一些消息,其中包括违规论点的名称。否则,方法的调用方将不得不查看代码以了解出了什么问题。(A NullPointerException 如果没有消息,则会产生一个异常,其中包含相当荒谬的消息“null”)。

    testNullOrEmptyString参数

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

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

    然而,上面的模板有一个问题,即如果in参数是最终参数,则必须对生成的代码进行一些修改( ${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”或类似的结果有趣得多,实际上可能会给用户一个解决问题的机会。

    享受

        29
  •  4
  •   Dan TheCodeJunkie    17 年前

    我将其用于MessageFormat(使用Java1.4)。这样,我就可以确保在进行国际化时不会出现难以提取的连接

    i18n

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

    同样用于日志记录:

    日志

    if(logger.isDebugEnabled()){
      String msg = "${message}"; //NLS-1
      Object[] params = {${params}};
      logger.debug(MessageFormat.format(msg, params));
    }
    
        30
  •  4
  •   jeff porter    16 年前

    我最喜欢的几个是。。。

    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并将缓冲区的内容写入一个文件。 用于将缓冲区与过去的运行进行比较(使用BeyondCompre),或者由于缓冲区太大而无法查看缓冲区的内容(通过inspect)。。。

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