How to Create a "File Template", for java code, in a new NetBeans Module?

1.2k Views Asked by At

I've taken the well-known Netbeans tutorial "NetBeans File Template Module Tutorial" which shows how to create an HTML template, shareable via a module. It worked fine, but when I attempted to create a Java template using a java file instead of an html file for a template, I get unrecognized character errors. There must be a way to create a java source code template? Note: this is not a "Code Template" or a "Code Generator", which are similar features in NetBeans, but not the same.

Example template code, copied from the NetBeans default Java template:

<#if package?? && package != "">
package ${package};

</#if>
/**
 *
 * @author ${user}
 */
public class ${name} {

}
1

There are 1 best solutions below

1
On

I've found the solution to my own question.

It's found in the JavaDoc for org.netbeans.api.templates Annotation Type TemplateRegistration.

In your module's "package-info.java", the @TemplateRegistration annotation has an argument of content. Add ".template" to the end of the template file name (i.e. "CustomJava.java", becomes "CustomJava.java.template"). Also, name your template file the same way. This prevents the IDE from interpreting the FreeMarker template file as a Java file.

Other than that, all is the same as in the previously mentioned tutorial "NetBeans File Template Module Tutorial"

Example using "CustomJava" as the template name:

@TemplateRegistration (
folder = "Other",
iconBase = "customjava/icon.png",
displayName = "#CustomJava_displayName",
content = "CustomJava.java.template",
description = "Description.html",
scriptEngine = "freemarker")