Search code examples
netbeanscode-templates

How to get current class name in Netbeans code template?


I want to write code template for logger in Netbeans:

org.slf4j.LoggerFactory.getLogger(XXXXXX.class).warn("${cursor}");

I can't find syntax to insert current class name into template (see XXXXXX placeholder above) in reference.


Solution

  • I have created the following code template:

    private static final ${LOGGER_TYPE type="org.slf4j.Logger" default="Logger" editable=false} LOGGER = ${LOGGER_FACTORY type="org.slf4j.LoggerFactory" default="LoggerFactory" editable=false}.getLogger(${CLASS editable="false" currClassName}.class);
    

    and I have associated it to the abbreviation log.

    So at the cursor:

    ...
    public class MyClass {
        |
    ...
    

    I type log + TAB and NetBeans expands the text:

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    ...
    public class MyClass {
        private static final Logger LOGGER = LoggerFactory.getLogger(MyClass.class);
    ...
    

    I have also:

    • logd + TAB
    • logw + TAB
    • logi + TAB
    • loge + TAB

    coded as:

    ${LOGGER_CONST default="LOGGER" editable=false}.debug("${logMessage}");
    ${LOGGER_CONST default="LOGGER" editable=false}.warn("${logMessage}");
    ${LOGGER_CONST default="LOGGER" editable=false}.info("${logMessage}");
    ${LOGGER_CONST default="LOGGER" editable=false}.error("${logMessage}", ex);
    

    that generate:

    LOGGER.debug("logMessage");
    LOGGER.warn("logMessage");
    LOGGER.info("logMessage");
    LOGGER.error("logMessage", ex);