Creating new live-templates with import statements in IntelliJ IDEA

前端 未结 4 919
广开言路
广开言路 2021-02-02 06:06

Here is the Eclipse template that I want to port:

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


        
相关标签:
4条回答
  • 2021-02-02 06:08

    Just to save a little time for new visitors here: the accepted answer now needs some changes.
    Go to Settings -> Editor -> Live Templates, select others, add a template:

    private static final org.apache.logging.log4j.Logger logger = org.apache.logging.log4j.LogManager.getLogger($CLASS_NAME$.class);$END$
    

    Then, press Edit Variables on the left and set expression for CLASS_NAME to className().
    After all, set context on the bottom to Java -> Declaration (and Groovy -> Declaration if desired). Imports will be magically generated on insert.

    0 讨论(0)
  • 2021-02-02 06:09

    According to this post, it is intended to use only full-qualified expressions. I tried it out and this worked for me:

    private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger($CLASS_NAME$.class);$END$
    

    IDEA automatically shortens it and adds the necessary import statements:

    import org.apache.log4j.Logger;
    // ...
    private static final Logger LOG = Logger.getLogger(MyClass.class);
    

    If you want to try yourself, note that you first have to define CLASS_NAME as className() via Edit variables. Also make sure that you allowed your Live Template for Java declarations via Change (at the bottom). Here is a screenshot with the final setup:

    0 讨论(0)
  • 2021-02-02 06:10

    Now its possible to add live templates with static imports:

    You have to check static import in Options

    @org.junit.Test
    public void should$EXPR$when$CONDITION$() {
        org.junit.Assert.assertThat(null, org.hamcrest.CoreMatchers.is(org.hamcrest.CoreMatchers.nullValue())); 
    }
    

    0 讨论(0)
  • 2021-02-02 06:20

    For apache commons logging use:

    private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog($CLASS_NAME$.class);$END$
    
    0 讨论(0)
提交回复
热议问题