簡體   English   中英

Eclipse:Java類模板

[英]Eclipse: Java class templates

在Eclipse 3.5中,在Windows - > Preferences - > Java> Editor - > Templates下,我可以添加代碼模板。 但是,這些模板只能包含我可以插入到現有Java類中的代碼段。

是否可以為整個Java類創建模板,我可以使用File - > New - > My-Java-Class添加它們?

你能做的是添加一個普通的代碼快捷方式(java - > editor - > templates),

即使編輯器模板“newcustomclass”成為您正在討論的類的內容。

然后以正常方式創建新的java類,刪除所有內容,然后使用“newcustomclass”代碼模板創建新的自動java類。

這是一個簡單異常類的示例:

public class ${enclosing_type} extends Exception {

    /**
     * Constructs with the given throwable
     * @param t the throwable to throw
     */
    public ${enclosing_type}(Throwable t) {
        super(t);
    }

    /**
     * Constructs with the given message
     * @param message the message of the exception
     */
    public ${enclosing_type}(String message) {
        super(message);
    }

    /**
     * Constructs with the given message and the original throwable cause
     * @param message the message of the exception
     * @param t the original throwable
     */
    public ${enclosing_type}(String message, Throwable t) {
        super(message, t);
    }
}

您可以在eclipse中添加“ 新文件向導 ”,但是您需要編寫一個新插件來執行此操作。 我不知道在運行時以MS Office模板的方式執行此操作的簡單方法,我認為這是您正在嘗試執行的操作。

一個新的模板機制可能是一個有用的插件,但我找不到任何已經這樣做的東西。

是! 窗口 - >首選項 - > Java - >代碼樣式 - >代碼模板

在樹面板中選擇“代碼”和新的Java文件。

想要做類似的事情我最終采用類似的方法使用Java編輯器模板邁克爾威爾斯答案。 但是我必須使用$ {primary_type_name}而不是$ {enclosingType}來填充類名。 根據我的經驗,在輸入模板命令之前刪除所有內容后,$ {enclosingType}將丟失類名。 這是與eclipse版本:2.2.500.v20190307-0500

例如,以下是創建模板命令以創建啟用了Lombok日志記錄的新Spring Service的步驟。

1)首先我們必須創建一個Java Editor模板Preferences->Java->Editor->Template
*輸入create-spring-service作為名稱
*為上下文字段選擇Java
*在Pattern字段中輸入以下模板。

package ${enclosing_package};

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ${primary_type_name} {
    ${cursor}
}

2)創建一個新類。
3)打開新類並選擇所有ctl -> a
4)然后通過點擊ctl -> space調用模板並開始輸入模板名稱create-spring-service

注意:在Pattern字段中鍵入template時,您可以鍵入$或hit ctl -> space來查看預定義模板變量的列表。

在線可用模板變量列表

您可以嘗試使用這個eclipse 插件,它可以創建一個包含許多可配置參數的Java類,例如注釋或XML配置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM