Creating new live-templates with import statements in IntelliJ IDEA

纵然是瞬间 提交于 2019-12-03 06:28:56

问题


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

My current version in IDEA is as follows:

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

where $CLASS_NAME$ is configured to use className() as its expression.

Unfortunately, I don't find any documentation on adding the import statement. Is there somehing equivalent to Eclipse ${:import(...)}?


回答1:


According to this post, it seems to be 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);



回答2:


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.




回答3:


For apache commons logging use:

private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog($CLASS_NAME$.class);$END$


来源:https://stackoverflow.com/questions/17190489/creating-new-live-templates-with-import-statements-in-intellij-idea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!