Author | Sharehub
Link | blog.xiaohansong.com/idea-live-templates.html
Preface
The Java development process often needs to write code with a fixed format, such as declaring a private variable, logger or bean, and so on. For this small-scale code generation, we can use the Live Templates function provided by IDEA. At first I thought it was just a simple Code Snippet, but later discovered that it supports variable function configuration and can support very complex code generation.
Let me introduce the usage of Live Templates.
Basic use
IDEA comes with many commonly used dynamic templates, enter fori in the Java code, and the carriage return will appear
for (int i = 0; i < ; i++) {
}
Press Tab to jump to each blank and fill in the value manually.
Custom template
After all, the official built-in templates cannot meet the needs of our personal coding style. Live Templates provides variable functions for us to customize.
Simple usage
To add a custom template, you first need to fill in the trigger word (ie Abbreviation), the description is optional, and then define the context of the template, click define to select Java, so that the current template will be triggered when editing Java. After defining the context, You can fill out the template.
Here are a few simple templates I commonly use
==========
<out>
----------
System.out.println($END$)
==========
<pfs>
----------
private final static String $varName$ = "$var$";`
==========
<privateField>
----------
/**
* $COMMENT$
*/
@Getter
@Setter
private $TYPE$ $NAME$;
==========
<main>
----------
public static void main(String[] args) {
$END$
}
==========
The template supports the definition of variables, using $$
enclosed characters to represent a variable. $END$
It is a special predefined variable that indicates the position where the cursor jumps last. The position of each variable can be jumped over.
Advanced usage
If you have used the Code Sinppet plugin of vim, you will find that functions can be executed in the template. Of course, the powerful Live Templates also support it, and IDEA can perceive the semantics of the code, such as the parameters of the currently edited function. But this will allow us to play out. Let's study the function of template functions from easy to difficult.
The variables we mentioned earlier can be bound to functions, and the configuration method is shown in the figure above.
Declare variables quickly
Declaring variables is a common operation, especially when you need to declare variables that need to be annotated. When you comment, these codes are very boring to write. Here is the template I defined:
<osgiRef>
----------
/**
* $END$
*/
@OsgiReference
@Setter
private $TYPE$ $NAME$;
At first glance, this template looks similar to the privateField I defined above. The only difference is that I bind functions to these variables.
clipboard(): Returns the string of the current clipboard
decapitalize(): Change the first letter of the input string to lowercase
Let's demonstrate below, we first copy the current class name, and then enter osgiRef
Quickly declare logger
Declaring logger is also a common operation. Above we used the paste function to quickly declare variables. Now we will use another function className(). As the name suggests, its function is to return the current class name.
<logger>
----------
/** logger */
private static final Logger LOGGER = LoggerFactory.getLogger($CLASS$.class);
The most powerful groovyScript()
If the functions used above provide limited capabilities and are not flexible enough, then groovyScript() provides all the capabilities you want. It supports the execution of Groovy scripts to process input, and then output the processed string.
groovyScript("code", ...)
| code | 一段Groovy代码或者Groovy脚本代码绝对路径 |
| ... | 可选入参,这些参数会绑定到`_1, _2, _3, ..._n`, 在 Groovy 代码中使用。|
Let's take a look at its practical application.
Quick bean configuration
To add a new service, you must register a bean in Spring. Generally, this configuration is nothing more than specifying the id and class. Since we are configuring in xml, we cannot use the className() function, but we can use the clipboard() function to get it. For the full reference of the class, in IDEA, we directly right-click the class name and click Copy Reference. Then execute the groovy script to get the class name.
<bean>
----------
<bean id="$id$" class="$REF$" />
id binding decapitalize(groovyScript("_1.tokenize('.')[-1]", clipboard()))
, first take clipboard()
the value to get the full reference of the class, and then execute the groovy code _1.tokenize('.')[-1]
(press. to split into a string array, and then take the last one to get the class name, and then use decapitalize()
lowercase the first letter to get the id.
Quickly print current context information
When printing the error log, you need to print the current context information, such as input parameters. Sometimes when there are a lot of parameters, it is painful to write. Fortunately, there is a template function methodParameters(), which returns a list of current function parameters. Of course, this list is us. It cannot be used directly, it needs to be converted with groovyScript.
<printContext>
---------------
LogUtil.$TYPE$(LOGGER, "$MSG$ " + $params$);
Binding params to groovyScript("'\"' + _1.collect { it + ' = [\" + ' + it + ' + \"]'}.join(', ') + '\"'", methodParameters())
it will automatically format the parameters of the current function and output them.
to sum up
Above we briefly introduced the commonly used template functions. In fact, IDEA has many other template functions. For details, please refer to Creating and Editing Template Variables.
https://www.jetbrains.com/help/idea/2016.3/creating-and-editing-template-variables.html
IDEA is a very powerful tool. Good use of tools can greatly improve work efficiency and devote energy to key things instead of wasting time on writing repetitive code. Some more advanced usages are yet to be discovered. Finally, I promoted a wave of code generation plug-ins CodeMaker that I wrote, and making good use of it can save a lot of time for repetitive code writing.
PS: In addition, the editor has established a learning exchange group, which is forbidden to promote. The atmosphere in the group is very good. If you have any questions, you can also ask questions in the group. Friends in need can add it~
Plus group mode - scanning the bottom ???? author of the two-dimensional code, notes: plus group
Friends who like this article, please click on the picture to follow the subscription account and watch more exciting content!
Recommended reading:
"The mobile phone chase drama artifact, the latest hot movie is free to watch, very impressive! 》
" More than 200 computer repair tools ask you if you want? 》
"A long-collected black technology website with free software downloads "
" Recommend a few free learning websites to charge everyone! 》
" Some tools and websites that can greatly improve your work efficiency "
Click to see and then go!