Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating new live-templates with import statements in IntelliJ IDEA

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(...)}?

like image 332
Philipp Claßen Avatar asked Jun 19 '13 11:06

Philipp Claßen


People also ask

How do I automatically import imports in IntelliJ?

Automatically add import statements You can configure the IDE to automatically add import statements if there are no options to choose from. In the Settings/Preferences dialog ( Ctrl+Alt+S ), click Editor | General | Auto Import. Select the Add unambiguous imports on the fly checkbox, and apply the changes.

How do I create a project template in IntelliJ?

From the main menu, select File | New Projects Setup | Save Project as Template. In the dialog that opens, name the template and configure the options: Save: if the project contains more than one module, select whether you want to create a template from the whole project or from one of the modules.

How do I organize imports in IntelliJ?

In Eclipse, you press CTRL + SHIFT + O “Organize Imports” to import packages automatically. For IntelliJ IDEA, if you press CTRL + ALT + O “Optimize Imports”, it just removes some unused imports, never imports any package.


1 Answers

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:

enter image description here

like image 111
Philipp Claßen Avatar answered Sep 19 '22 12:09

Philipp Claßen