We will create a Sugar4j class that outputs the Hello World program:
1 |
For every class/code to generate, you'll create a subclass of Sugar4j. The type parameter is the subclass itself.
As a suggestion, the sugar class is named by appending the "Sugar" suffix to the name of the class that the sugar generates.
|
2 |
Calls the super constructor with the full qualified class name that this sugar class creates. |
3 |
Implement the doCreate() method. The content of this method forms the 'compilation unit' or simply the Java file that is to be generated. |
4 |
beginCompilationUnit() outputs the file header and the package declaration. This is most likely the first call you'll made within the doCreate() method. |
5 |
The class declaration. publicc() outputs the public modifier, classs() outputs the class keyword followed by the simple name of the sugar's class; it's the shorthand for classs(getClassSimpleName()) .
The begin() and end() methods outputs the beginning and ending of a block ({ } ). We strongly encourage you to use nested blocks within the begin() and end() calls to improve readability of the structure of the sugar class.
|
6 |
mainn() declares the well known main(String[]) method. |
7 |
Calls the method println on the object Systemout with the parameter quote("Hello world!") .
Systemout is the string constant "System.out" , declared in the sugar4j.lang.JavaLang interface, which is implemented by Sugar4j.
quote() instructs to output a string literal.
eos() - EndOfStatement - instructs to output a semicolon.
|
8 |
Creates a new HelloWorldSugar instance, calls create() to generated it's content and prints out the content. The Sugar4j's toString() method is overridden so that it returns the content generated so far.
Note the full qualified name to address java.lang.System . This is necessary because Sugar4j declares a System string constant which shadows the java.lang.System identifier.
|
As you can see, Java code that is to be generated (the template code) resides in the same class as your dynamic code. There is no need for external template files like .jsp/.php/.jet and the like.