본문으로 바로가기

IntelliJ에서 이클립스의 코드 템플릿(Code Templates) 기능같이 자동으로 Type(Class 등)이나 Method에 사전에 설정한 주석을 자동으로 생성하는 방법을 포스팅 합니다.

이클립스(STS)의 코드 템플릿 기능에 대한 내용은 아래 포스팅을 참조해주세요.

 

[Eclipse] 주석 템플릿 설정하기 (템플릿 공유)

이클립스(Eclipse)나 STS에서 메서드나 클래스에 주석을 통해 코멘트를 작성할때 코드 템플릿(Code Template) 기능을 이용하면 자동으로 주석(Comment)를 생성하여 쉽게 작성 할 수가 있습니다. 클래스나

ifuwanna.tistory.com

 1. Class (Type)

다르게 Type에 속하는 Class의 주석(Commnet)은 규 파일 생성시점에만 자동으로 생성이 가능합니다.

1. Preferences > Editor > File and Code Templates 메뉴에 들어가시면 각 속성의 파일이 생성될 때 자동으로 생성해줄 템플릿을 확인하실 수 있습니다. 파일 생성시 가장 상단에는 ${PACKAGE_NAME} 치환자를 통해 패키지명이 자동으로 들어가게 되고 Class명 상단에는#parse("File Header.java") 치환자를 통해 File Header.java 안에 있는 주석(Commnet)내용이 자동으로 생성됩니다. 

2.#parse("File Header.java")에 치환되는 데이터는 Includes 탭으로 이동하면 File Header.java 파일을 열어 상세 주석 내용을 확인 하고 수정할 수 있습니다.

/**
 *packageName    : ${PACKAGE_NAME}
 * fileName       : ${NAME}
 * author         : ${USER}
 * date           : ${DATE}
 * description    :
 * ===========================================================
 * DATE              AUTHOR             NOTE
 * -----------------------------------------------------------
 * ${DATE}        ${USER}       최초 생성
 */

 

템플릿 작성시현재 상태의 특정 값으로 확장할 수 있는 사전 정의 변수(Predefined variables)를 사용 할 수 있습니다. 아래는 자주 사용될 만한 확장 변수 목록입니다. 이 외에도 더 많은 Predefined variables에 대한 내용은 아래 링크를 잠고해 주세요.

Predefined variables will take the following values:
${PACKAGE_NAME} : name of the package in which the new file is created
${USER} : current user system login name
${DATE} : current system date
${TIME} : current system time
${YEAR} : current year
${MONTH} : current month
${MONTH_NAME_SHORT} : first 3 letters of the current month name. Example: Jan, Feb, etc.
${MONTH_NAME_FULL} : full name of the current month. Example: January, February, etc.
${DAY} : current day of the month
${DAY_NAME_SHORT} : first 3 letters of the current day name. Example: Mon, Tue, etc.
${DAY_NAME_FULL} : full name of the current day. Example: Monday, Tuesday, etc.
${HOUR} : current hour
${MINUTE} :current minute
${PROJECT_NAME}  : the name of the current project

 

 

Apache Velocity Engine - User Guide

User Guide - Contents About this Guide The Velocity User Guide is intended to help page designers and content providers get acquainted with Velocity and the syntax of its simple yet powerful scripting language, the Velocity Template Language (VTL). Many of

velocity.apache.org

3. 위 템플릿을 저장 후 com.leetcode.challenge.april 패키지 하단에 TemplatesTest라는 새로운 Java Class 파일을 만들어 보면 아래와 같이 사전에 저장한 템플릿에 맞춰 Comment가 자동으로 생성된 것을 확인 하실 수 있습니다.

 2. Method 주석 

메서드는 기본적으로 이클립스처럼 원하는 형태의 comment를 생성하는 기능은 없고 JavaDoc Plugin 확장을 이용하여 유사하게 구현할 수 있습니다.

1. Preferences > Plugins >JavaDoc 플러그인을 설치해 주세요

2. JavaDoc 플러그인 설치가 끝나면 Preferences>JavaDoc >Templates 탭으로 들어가 주세요. 해당 탭에서 정규식을 통해 원하는 주석 내용을 사전에 세팅하여 자동 생성 할 수 있습니다.

 

3. 템플릿을 적용할 단어에 정규식 을 지정해 준뒤 생성할 Template content를 지정할 수 있습니다. Javadoc templates은 프리마커 템플릿(freemarker template engine)을 기반으로 하기 때문에 apache의 freemarker  프리마커 라이브러리(2.3.23 버전)에서 사용할 수 있는 기본 제공 변수를 모두 사용할 수 있습니다.

https://github.com/setial/intellij-javadocs/wiki/Javadoc-templates
https://github.com/setial/intellij-javadocs/wiki

The following variables are available in any template:
• name - Name of element splitted by character type in camel case. For example if classname: SomeClass - name variable in template will have the "Some class" value.
• partName - Name of element splitted by character type in camel case without first item in split array. This can be usefull for the getter/setter methods. In this case for the method name getSomeText the partName variable will have "Some text" value.
• splitNames - Array of strings split element name by character type in camel case.
• element - this is an element of code for javadoc. This is a part of intellij idea API. For example for Class level javadoc here will be PsiClass, for method or constructor - PsiMethod, for field - PsiField.

Additionally for method level javadocs the following variables are available:
• fieldName - usefull for getter/setter methods. It contains field name for generated method.
• isNotVoid - type boolean. Shows whether method is void or not.
• return - this variable contains string of return type splitted like it was in name variable.
• paramNames - this variable contains strings map of parameter names splitted like it was in name variable (key of map is name of parameter, value is splitted value of parameter name).
• exceptionNames - this variable contains strings map of exception types splitted like it was in name variable (key of map is name of exception, value is splitted value of exception type).

Additionally for field level javadocs the following variables are available:
• typeName - name of the class where fields is located.

Other variables:
• You can use all built in variables that are available in freemarker library (2.3.23 version): http://freemarker.incubator.apache.org/docs/ref_builtins.html
/**\n
* methodName    : ${element.getName()}\n
* author        : Jihun Park\n
* description   : \n
<#if element.typeParameters?has_content>       
* \n
</#if>
<#list element.typeParameters as typeParameter>
         * @param <${typeParameter.name}> the type parameter\n
</#list>
<#if element.parameterList.parameters?has_content>
         *\n
</#if>
<#list element.parameterList.parameters as parameter>
         * @param ${paramNames[parameter.name]}\n
</#list>
<#if isNotVoid>
         *\n
         * @return ${return}\n
</#if>
<#if element.throwsList.referenceElements?has_content>
         *\n
</#if>
<#list element.throwsList.referenceElements as exception>
         * @throws ${exception.referenceName} the ${exceptionNames[exception.referenceName]}\n
</#list>
 */

4. 위 메서드 템플릿 지정 후 실제로 3개의 인자를 받는 templateTest() 메서드 에 대한 주석(JavaDoc)을 생성해 보도록 하겠습니다.

메서드를 선택 후 Generate > Create JavaDocs for the selected element 를 선택하면 해당 메서드에 대한 자동으로 주석이 생성됩니다.  Create JavaDoecs for all elements 를 이용하면 현재 파일의 모든 메서드에 대한 주석을 생성 할 수도 있습니다.