前言
Java 開發過程中經常會遇到編寫重復代碼的事情,例如說:編寫領域類和持久類的時候,大部分時候它們的變量名稱,類型是一樣的,在編寫領域類的時候常常要重復寫類似的代碼。類似的問題太多……這里介紹一個 IDEA 的代碼生成插件,通過 Velocity 支持自定義代碼模板來生成代碼。
項目地址:CodeMaker
https://github.com/x-hansong/CodeMaker
主要功能
支持增加自定義代碼模板(Velocity)
支持選擇多個類作為代碼模板的上下文
安裝
下載插件:CodeMaker.zip
https://github.com/x-hansong/CodeMaker/releases/download/1.0/CodeMaker.zip
-
打開設置,選擇“Plugin”
-
在右邊的框中點擊“Install plugin from disk”
-
選擇上面下載的“CodeMaker.zip”
-
點擊“Apply”,然后重啟 IDEA。
使用
在 Java 類編輯界面右鍵“Generate”,選擇對應模板即可自動生成代碼到當前類的包,大部分情況下生成的代碼已經解決了百分之八十的問題,只需稍作修改,移動到合適的包中,就能快速完成代碼編寫。
如果代碼模板需要除了當前類之外的類作為上下文,可以通過類選擇框進行選擇。
目前自帶的兩個模板:
-
Model:根據當前類生成一個與其擁有類似屬性的類,用於自動生成持久類對應的領域類(在持久類擁有超過10個屬性的情況下,能夠節省大量時間)。
-
Converter:該模板需要兩個類作為輸入的上下文,用於自動生成領域類與持久類的轉化類。
上面兩個模板是我自己工作中常用的模板,僅供大家參考,自帶的模板可能滿足不了大家的需求,所以插件支持自定義新的代碼模板。
模板配置
-
增加模板:點擊“Add Template”后,填寫相關配置(都不能為空),點擊保存后即可生效,無需重啟。(感謝khotyn提醒)
-
刪除模板:點擊“Delete Template”就能將該模板刪除
-
Template Name:在生成菜單中顯示的名稱,英文命名
-
Class Number:該模板需要的輸入上下文類的數量,例如:如果為 1,,將當前的類作為輸入:$class0;如果為 2,需要用戶再選擇一個類作為輸入:$class0, $class1。
-
Class Name:生成的類的名稱,支持通過 Velocity 進行配置,上下文為跟代碼模板的相同。
模板上下文
模板上下文包含了以下變量:
########################################################################################
##
## Common variables:
## $YEAR - yyyy
## $TIME - yyyy-MM-dd HH:mm:ss
## $USER - user.name
##
## Available variables:
## $class0 - the context class
## $class1 - the selected class, like $class2, $class2
## $ClassName - generate by the config of "Class Name", the generated class name
##
## Class Entry Structure:
## $class0.className - the class Name
## $class0.packageName - the packageName
## $class0.importList - the list of imported classes name
## $class0.fields - the list of the class fields
## - type: the field type
## - name: the field name
## - modifier: the field modifier, like "private"
## $class0.methods - the list of class methods
## - name: the method name
## - modifier: the method modifier, like "private static"
## - returnType: the method returnType
## - params: the method params, like "(String name)"
##
########################################################################################
具體用法可參考自帶的代碼模板,通過模板上下文提供的定制能力,可以讓每個用戶都定制自己的風格的代碼模板。
來源:http://blog.xiaohansong.com/2017/02/03/codemaker/