How to automatically generate code for Java advanced

Source: Internet
Author: User

First, Preface: Why should have the code automatic generation?
The simplest and most straightforward answer to this question is: Instead of writing code manually, improve productivity.

What scenarios and codes are appropriate for automatic generation of this method?
A friend of the Java server must know that we need to write Java entity classes (entities) with database table mappings, and to write the DAO class corresponding to the entity (the Xxdao.java class contains the increment, delete, change, and check basic operations of the corresponding entity). In these entity classes are usually some property methods and properties corresponding to the Get/set method, and the entity corresponding to the DAO class will also basically include the increment, delete, change, check these and database operations related methods. In the process of writing so many entity classes and DAO classes, have you found that there are many places in the code that are similar, or almost, just different names? Yes, well, at this point we can actually define a template and let the code be generated automatically by the template.

Ii. Brief introduction of Freemarker
Before entering the text, let's start with a quick and easy look at Freemarker.
(The Web development of friends must be quite familiar, small Lu was also in the Web development when the first contact with Freemarker)
1. Overview: Freemarker is a template engine: a template-based, generic tool for generating output text. More is to be used to design the generated HTML page.

To put it simply: Freemarker is to use a template to generate a text page to render the prepared data. As stated


Freemarker Official website: http://freemarker.org/

2. A simple example showing how to use Freemarker to define a template, bind model data, and generate an HTML page for final display:
1>. New project Create a new "template" folder under the project root to store our template file.

If we create a new template file TEST.FTL content as follows:

2>. Project Introduction Freemarker.jar (: https://jarfiles.pandaidea.com/freemarker.html),
Use the Freemarker API method in Java classes to reference template files, create data models, merge data models with template file final input,

The code is as follows:

Import Java.io.file;import java.io.ioexception;import Java.io.outputstreamwriter;import Java.io.Writer;import Java.util.hashmap;import Java.util.map;import Freemarker.template.configuration;import Freemarker.template.defaultobjectwrapper;import Freemarker.template.template;import Freemarker.template.templateexception;public class Htmlgeneratorclient {public static void main (string[] args) {try { Configuration cfg = new configuration ();//Specifies where the template file is loaded from the data source, set here as a file directory Cfg.setdirectoryfortemplateloading (". /template ")); Cfg.setobjectwrapper (new Defaultobjectwrapper ());//Gets or creates a template templates = Cfg.gettemplate (" TEST.FTL ");//Create data Model Map root = new HashMap (); Root.put (" User "," Big Joe "); Map latest = new HashMap (), Root.put ("Latestproduct", Latest), Latest.put ("url", "products/greenmouse.html"); Latest.put ("name", "Green Mouse");//merge the template and data model into consolewriter out = new OutputStreamWriter (System.out); Template.process (root, out); Out.flush ();} catch (IOException e) {e.printstacktrace ();} CATCH (templateexception e) {e.printstacktrace ();}}} 

3> The page code for the resulting HTML is as follows:


Third, how to use Freemerker to complete the automatic generation of Java class code
In the example above, our FTL template file defines an HTML page template, so we define the FTL template as Java code, and the Java class can be generated by binding the data template.
Below LV will use templates to automate the creation of Java classes of entity objects (writing template files for entity classes is relatively logical and simple, but the most important thing is that we have to master its ideas)
1. Enumeration class for attribute types Propertytype.java

/** * Attribute type enum class * @author  [email protected] * */public enum PropertyType {Byte, short, Int, Long, Boolean, Float, Double , String, ByteArray, Date}
2, the Entity corresponding field attribute class Property.java
/** * Entity corresponding attribute class * @author  [email protected] * */public Class Property {//attribute data type Private String javatype;//property name Private String Propertyname;private PropertyType propertytype;public string Getjavatype () {return javatype;} public void Setjavatype (String javatype) {this.javatype = Javatype;} Public String Getpropertyname () {return propertyname;} public void Setpropertyname (String propertyname) {this.propertyname = propertyname;} Public PropertyType Getpropertytype () {return PropertyType;} public void Setpropertytype (PropertyType PropertyType) {this.propertytype = PropertyType;}}
3. Entity Model class Entity.java
Import java.util.list;/** * Entity class * @author [email protected] * */public class Entity {//entity contains the package name private String javapackage ;//entity class name private string classname;//parent class name private String superclass;//property collection List<property> properties;// Whether there is a constructor private Boolean constructors;public String Getjavapackage () {return javapackage;} public void Setjavapackage (String javapackage) {this.javapackage = Javapackage;} Public String GetClassName () {return className;} public void Setclassname (String className) {this.classname = ClassName;} Public String Getsuperclass () {return superclass;} public void Setsuperclass (String superclass) {this.superclass = superclass;} Public list<property> getProperties () {return properties;} public void SetProperties (List<property> properties) {this.properties = properties;} public Boolean isconstructors () {return constructors;} public void Setconstructors (Boolean constructors) {this.constructors = constructors;}}
4, in the project root directory to create a new "template" folder to store our template file, the new entity template ENTITY.FTL content as follows:
Package ${entity.javapackage};/** * This code was generated by Freemarker * @author [email protected] * */public class ${entity.classname}< #if entity.superclass?has_content> extends ${entity.superclass} </#if >{/********** Attribute ***********/< #list entity.properties as property> private ${property.javatype} ${    Property.propertyname};        </#list >/********** Constructors ***********/< #if entity.constructors> public ${entity.classname} () { } public ${entity.classname} (< #list entity.properties as Property>${property.javatype} ${property.propertyn ame}< #if property_has_next&gt, </#if ></#list >) {< #list entity.properties as property> thi    S.${property.propertyname} = ${property.propertyname}; </#list >}</#if >/********** get/set ***********/< #list entity.properties as property> public $ {Property.javatype} Get${property.propertyname?cap_first} () {return ${propertY.propertyname}; } public void Set${property.propertyname?cap_first} (${property.javatype} ${property.propertyname}) {This.${prop    Erty.propertyname} = ${property.propertyname}; } </#list;}
5. Automatically generate entity class client code Entitygeneratorclient.java
Import Java.io.file;import java.io.filewriter;import Java.io.ioexception;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.defaultobjectwrapper;import Freemarker.template.template;import freemarker.template.templateexception;/** * Auto-generated entity class client * @author [email  Protected] * */public class Entitygeneratorclient {private static File Javafile = Null;public static void Main (string[] Ar GS) {Configuration cfg = new Configuration (); try {//Step one: Specify the data source from where the template file is loaded, set a file directory cfg.setdirectoryfortemplateloading (New file ("./template")); Cfg.setobjectwrapper (new Defaultobjectwrapper ());//Step two: Get template file templates Cfg.gettemplate ("ENTITY.FTL");///Step three: Create a data Model map<string, object> root = Createdatamodel ();//Step four: Merge templates and Data models//create. J Ava class file if (Javafile! = null) {Writer javawriter = new FileWriter (javafile); template.process (Root, jaVawriter); Javawriter.flush (); SYSTEM.OUT.PRINTLN ("File generation path:" + Javafile.getcanonicalpath ()); Javawriter.close ();} Output to console console writer out = new OutputStreamWriter (System.out); template.process (root, out); Out.flush (); Out.close ();} catch (IOException e) {e.printstacktrace ();} catch (Templateexception e) {e.printstacktrace ()}} /** * Create data Model * @return */private static map<string, object> Createdatamodel () {map<string, object> root = new Hashmap<string, object> (); Entity user = new entity (); User.setjavapackage ("com.study.entity");  Create the package name User.setclassname ("User"); Create Class name User.setconstructors (TRUE); Whether to create a constructor//User.setsuperclass ("person"); list<property> propertylist = new arraylist<property> ();//Create an entity attribute Attribute1 = new property (); Attribute1.setjavatype ("String"); Attribute1.setpropertyname ("name"); Attribute1.setpropertytype ( propertytype.string);//Create entity attribute two Property Attribute2 = new Property (); Attribute2.setjavatype ("int"); Attribute2.setpropertyname ("Age"); Attribute2.setpropertytype (Propertytype.int);p ropertylist.add (attribute1);p ropertylist.add (ATTRIBUTE2);// Adds a collection of properties to the entity object User.setproperties (propertylist);//Creates a. Java class file Outdirfile = New File ("./src-template"); Outdirfile.exists ()) {Outdirfile.mkdir ();} Javafile = Tojavafilename (Outdirfile, User.getjavapackage (), User.getclassname ()); Root.put ("entity", user); return Root;}  /** * Create. java file path and return. Java File Object * @param outdirfile Makefile Path * @param javapackage java package name * @param javaclassname Java class name  * @return */private static file Tojavafilename (file Outdirfile, String javapackage, String javaclassname) {string        Packagesubpath = Javapackage.replace ('. ', '/');        File PackagePath = new file (Outdirfile, Packagesubpath);        File File = new file (PackagePath, Javaclassname + ". Java");        if (!packagepath.exists ()) {packagepath.mkdirs ();    } return file; }}
6. Run the program we will generate the folder Src-template and automatically generated entity classes in the project root directory User.java
as follows:
After---run--->

< Program pre-run directory structure > < program after run directory structure >

The automatically generated entity class User.java code is as follows:

Package com.study.entity;/** * This code was generated by Freemarker * @author [email protected] * */public class user{
   
    /********** attribute ***********/    private String name;        private int age;        /********** Constructors ***********/Public    user () {        } public    User (String name, Int. age) {        this.name = n Ame;        This.age = age;    }    /********** get/set ***********/public    String getName () {        return name;    }    public void SetName (String name) {        this.name = name;    }        public int getage () {        return age;    }    public void Setage (int.) {        this.age = age;    }    }
   


Four, the reflection behind

We learned from the two simple examples above that the so-called auto-generated code is actually:

1. define Java class template file 2, define template Data 3, reference template file (. ftl) Merge with template data to generate Java classes .

Some of the friends in the above example might be asking if they want to write an entity object? Why bother, build. ftl files, and write so many classes, the process of defining template data is so troublesome, I might as well write manually, declare a few properties, set/get shortcut keys to write all at once. Is that really the case?
Think in terms of an auxiliary tool and software architecture, and assume that a development helper or plug-in completes the automatic generation of entity classes and corresponding DAO classes. Suppose you need to build 10 entity classes and a DAO class that contains the basic operations of adding additions and deletions. I write the package name, class name, attribute field and other information in the C/S client and then generate it with a key, and think about how cool and happy one thing is (assuming that your template class is very powerful and versatile), and you may still keep CTRL + C and CTRL + V.

V. Other
about how to write the. FTL template file, you need to go through the data self-study!

Retinues still provide Freemarker official website: http://freemarker.org/




How to automatically generate code for Java advanced

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.