intellj idea的強大之處就不多說了,相信每個用過它的人都會體會到,但是我們也會被他的復雜搞的暈頭轉向,尤其剛從eclipse轉過來的童鞋,相信剛開始的那段經歷都是不堪回首的,我也是一步步這么走過來的。
今天講的一個主題是如何實現類似eclipse的Code Templates那樣的功能,進行文件級別的方法級別注釋的實現。
一:文件級別的注釋
文件級別的注釋網上已經很多介紹了,本文不做多介紹,主要是通過File--》Setting--》File and Code Template中來設置

二:方法級別的注釋
文件級別的注釋網上其實已經有很多了,但是方法級別的注釋講解的卻很少,很多人不知道如何實現。我分享的這種方法也是個人在使用Intellj過程中自己的一些技巧,如果你有更好的方式,可以在評論中給予更多的思路。主要就是通過intellj強大的Live Template來做。
下面簡單介紹一下Live Template(下面這段話摘自網絡,點擊這里進入原文-- 更為詳細的Live Template的使用介紹和高級進階,請參考文章底部鏈接 ):
用慣了Eclipse快捷鍵的人可能會不習慣,sysout、foreach等快捷方式找不到了,main方法也無法自動補全了,其實這個在IntelliJ中有一個異常強大的模塊Live Template來實現。
例如,在class中嘗試psvm+tab,則會發現main方法產生了;輸入iter+tab,則生成了foreach語句。
live template還有一個surround的用法,選中某個變量,鍵入ctl+alt+j兩次,則會出現自動補全的菜單。
此外,還可以自定義Live Template。Code Snippet技術應用也挺普遍的,IntelliJ的Live Template優點是內置了一些智能的變量和函數,可以做到一些語義級別的分析和運用
下面為具體步驟:
1、點擊File--》Setting--》Live Template,點擊右側的+號,選擇Template Group

2、輸入MyGroup(你也可以輸入其他自定義的名稱),然后點擊OK。

3、選中MyGroup之后,再次點擊右側的+號,選擇Live Template


其中abbreviation
4、點擊第四步的Define,選擇EveryWhere

5、點擊右邊的Edit variables

6、點擊OK,Apply,退出,大功告成。在方法前面按 Ctrl+J ,然后選擇自定義的方法注解,進行體驗吧
我的上面的這個小技巧只是個人在使用Intellj時的一個小技巧而已,Live Template的使用,可以參考以下鏈接,建議大家仔細閱讀,對自己的常用編碼很有幫助。
IntelliJ下使用Code/Live Template加快編碼速度:程序員的工作不是寫程序,而是寫程序解決問題
Intellj Live Template中的預定義函數列表
備注:
注意點:
不知道怎樣可以帶回參數和返回值等信息,但是我知道為啥不顯示了。
user()和date()能顯示內容,是因為這兩個方法在其有效的作用域執行。
而關於Method的方法(如methodName()、methodParameters()、methodReturnType())沒有起作用是因為你在方法外執行的mc快捷操作,這些方法的作用域是在方法內。
看下methodName()方法的解釋:Returns the name of the embracing method (where the template is expanded).返回起作用的方法的名稱。
| This is a built-in template. It contains a code fragment that can be included into file templates (Templates tab) with the help of the #parsedirective. The template is editable. Along with static text, code and comments, you can also use predefined variables that will then be expanded like macros into the corresponding values. |
| 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 | |
| ${HOUR} | current hour | |
| ${MINUTE} | current minute | |
| ${PROJECT_NAME} | the name of the current project |
注意點二:多個參數換行,可以使用 groovyScript



其中腳本值:
groovyScript("def result=''; def params=\"${_1}\".replaceAll('[\\\\[|\\\\]|\\\\s]', '').split(',').toList(); for(i = 0; i < params.size(); i++) {result+=' * @param ' + params[i] + ((i < params.size() - 1) ? '\\n\\b' : '')}; return result", methodParameters())
