Using Freemarker to generate Java source code

Source: Internet
Author: User
Tags flush
a Freemarker introduction

Apache Freemarker is a Java Template Engine library, official website: http://freemarker.incubator.apache.org/.

Apache Freemarker is a template engine:a Java library to generate
Text Output (HTML Web pages, e-mails, configuration files, source
Code, etc.) Based on templates and changing data. Templates are
Written in the Freemarker Template Language (FTL), which are a simple,
Specialized language (not a full-blown programming language like PHP).
You are meant to prepare the ' data to display ' real programming
Language, like issue database queries and do business calculations,
And then the template displays that already prepared data. In the
Template you are focusing in how to present the data, and outside the
Template you are focusing in what data to present.

This approach was often referred to as the MVC (Model View Controller)
Pattern, and are particularly popular for dynamic Web pages. It helps
In separating the Web page designers (HTML authors) from the
Developers (Java programmers usually). Designers won ' t face
Complicated logic in templates, and can change the appearance of a
Page without programmers has to or recompile code.

While Freemarker is originally created for generating HTML pages in
MVC Web application frameworks, it isn ' t bound to servlets or HTML or
Anything web-related. It ' s used in non-web application environments as
Well.

template is the common (fixed) things extracted from the repeated use, save time to improve development efficiency. Now the mainstream template technology includes: Freemarker and velocity, template technology is highly recommended a pattern: output = template + data.
Freemarker was initially used by the MVC Web framework to generate HTML pages, but its purpose was not limited to the HTML or web domain, such as the generation JavaBean source code introduced in this article. two generate JavaBean source code

This article will use Freemarker to generate Person.java class code as follows:

Package Com.ricky.java;

Import java.util.List;

/**
 *  @author Ricky Fung * * Public
class Person {
    private Long ID;
    private String name;
    Private Integer age;
    private list<string> hobby;

    public void SetId (Long id) {
        this.id = ID;
    }
    Public Long GetId () {return
        this.id;
    }

    public void SetName (String name) {
        this.name = name;
    }
    Public String GetName () {return
        this.name;
    }

    public void Setage (Integer age) {
        this.age = age;
    }
    Public Integer Getage () {return
        this.age;
    }

    public void Sethobby (list<string> hobby) {
        this.hobby = hobby;
    }
    Public list<string> Gethobby () {return
        this.hobby;
    }

}

2.1 Introduction of Freemarker Dependence

<dependency>
            <groupId>org.freemarker</groupId>
            <artifactid>freemarker</ artifactid>
            <version>2.3.23</version>
        </dependency>

2.2 Freemarker Template file Person.ftl

Package ${packagename};

Import java.util.List;

/**
 *  @author ${author} */public
class ${classname} {
    < #list attrs as attr> 
    private $ {attr.type} ${attr.name};
    </#list >

    < #list attrs as attr> public
    Void Set${attr.name?cap_first} (${attr.type} ${attr.name} ) {
        This.${attr.name} = ${attr.name};
    }
    Public ${attr.type} Get${attr.name?cap_first} () {return
        this.${attr.name};
    }

    </#list >
}

2.3 Create A configuration instance

Configuration cfg = new Configuration (configuration.version_2_3_22);
        Cfg.setdirectoryfortemplateloading (templatedir);    
        Cfg.setdefaultencoding ("UTF-8");
        Cfg.settemplateexceptionhandler (Templateexceptionhandler.rethrow_handler);

2.4 Create a Data-model
1 in simple cases you can build data-models using Java.lang and Java.util classes and custom Javabeans:use Ng for Strings. Use Java.lang.Number descents for numbers. Use Java.lang.Boolean for Boolean values. Use the java.util.List or Java arrays for sequences. Use Java.util.Map for hashes. Use your custom bean class for hashes where the items are correspond to
The bean properties. For example the Price property (GetProperty ())
of product can get as Product.price. (The actions of the beans can
be exposed as; More than later here)

2 code-building data Model

map<string, object> root = new hashmap<string, object> ();

        Root.put ("PackageName", "Com.ricky.java");
        Root.put ("ClassName", "person");
        Root.put ("Author", "Ricky Fung");

        list<attribute> attr_list = new arraylist<attribute> ();
        Attr_list.add (New Attribute ("id", "Long");
        Attr_list.add (New Attribute ("name", "String");
        Attr_list.add (New Attribute ("Age", "Integer");
        Attr_list.add (New Attribute ("hobby", "list<string>"));

        Root.put ("Attrs", attr_list);

2.5 Getting the specified template

Template temp = cfg.gettemplate ("PERSON.FTL");

At this point, the PERSON.FTL is found in the E:/work/freemarker/templates directory.

2.6 Rendering templates with data

Writer out = new OutputStreamWriter (system.out);
Temp.process (root, out);

If you need to serialize the results to your hard disk, you can use the following code:

File dir = new file ("e:/work/freemarker/src/");
        if (!dir.exists ()) {
            dir.mkdirs ();
        }
        OutputStream fos = new  fileoutputstream (new file (dir, "Person.java");//java file's build directory   
        Writer out = new Outputstre Amwriter (FOS);
        Temp.process (root, out);

        Fos.flush ();  
        Fos.close ();

Finally, paste in the Codegenerator.java complete code

Package com.ricky.spring.springdemo.freemarker;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.OutputStream;
Import Java.io.OutputStreamWriter;
Import Java.io.Writer;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;

Import Java.util.Map;
Import freemarker.template.Configuration;
Import Freemarker.template.Template;
Import freemarker.template.TemplateException;

Import Freemarker.template.TemplateExceptionHandler; public class CodeGenerator {public static void main (string[] args) {try {new CodeGenerator ().
        Gen ();
        catch (IOException e) {e.printstacktrace ();
        catch (Templateexception e) {e.printstacktrace (); } public void Gen () throws IOException, templateexception{Configuration cfg = new Configuration (confi Guration.
        VERSION_2_3_22); Cfg.setdirectoryfortemplateloading (New File ("E:/work/freemarker/templaTES "));
        Cfg.setdefaultencoding ("UTF-8");

        Cfg.settemplateexceptionhandler (Templateexceptionhandler.rethrow_handler);  Template temp = cfg.gettemplate ("PERSON.FTL"); Load E:/WORK/FREEMARKER/TEMPLATES/PERSON.FTL//Create The root hash map<string, object> root =

        New hashmap<string, object> ();
        Root.put ("PackageName", "Com.ricky.java");
        Root.put ("ClassName", "person");

        Root.put ("Author", "Ricky Fung");
        list<attribute> attr_list = new arraylist<attribute> ();
        Attr_list.add (New Attribute ("id", "Long");
        Attr_list.add (New Attribute ("name", "String");
        Attr_list.add (New Attribute ("Age", "Integer");

        Attr_list.add (New Attribute ("hobby", "list<string>"));

Root.put ("Attrs", attr_list);
Writer out = new OutputStreamWriter (System.out);
        Writer out = new OutputStreamWriter (System.out); File dir = new file ("E:/work/freemarker/sr");
        if (!dir.exists ()) {dir.mkdirs (); OutputStream fos = new FileOutputStream (New File (dir, "Person.java"));
        Java file generation directory Writer out = new OutputStreamWriter (FOS);

        Temp.process (root, out);  
        Fos.flush ();

        Fos.close ();
    System.out.println ("Gen Code success!");
 }
}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.