Powerful IDEA code generator, learn how to use it, it's so fragrant!

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 kind of 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.

note

 

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>

----------

privatefinalstatic 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 characters enclosed by $$ to represent a variable. 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.

1.clipboard(): Returns the string of the current clipboard

2.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 */

privatestaticfinal 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 | Absolute path of a piece of Groovy code or Groovy script code |

| ... | Optional input parameters, these parameters will be bound to `_1, _2, _3, ..._n`, used in Groovy code. |

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 bind decapitalize(groovyScript("_1.tokenize('.')[-1]", clipboard())), first take the value of clipboard() to get the full reference of the class, and then execute the groovy code_1.tokenize( '.')[-1] (Press. To split into an array of strings, then take the last one to get the class name, and then use decapitalize() to lower 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$);

Bind params to groovyScript("'"' + _1.collect {it + '= [" +' + it + '+ "]'}.join(',') +'"'", methodParameters()) , The parameters of the current function can be automatically formatted and output.

 

to sum up

We briefly introduced the commonly used template functions above. 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, promote a wave of code generation plug-in CodeMaker (https://github.com/x-hansong/CodeMaker), making good use of it can also save a lot of time for rewriting code.

Guess you like

Origin blog.csdn.net/AI_mashimanong/article/details/109180631