How to automatically generate code in Java

Source: Internet
Author: User

How to automatically generate code in Java
I. Preface: Why is automatic generation of code required?
The most concise and direct answer to this question is: instead of writing code manually, improving work efficiency.

What scenarios and code are suitable for automatic generation?
Friends who have worked on the Java server must know that we need to write the Java Entity class (Entity) mapped to the database table in the Code and the DAO class (XxDao) corresponding to the object. java class contains the basic operations for adding, deleting, modifying, and querying corresponding entities ). These object classes are usually some property methods and get/set methods corresponding to the property, and the DAO class corresponding to the object also contains the addition, deletion, modification, and query of these and database operation-related methods. When writing so many entity classes and Dao classes, do you find that many of these codes are similar or similar, but their names are different? Yes. In this case, we can define a template and use the template to automatically generate the code.

Ii. Brief Introduction to FreeMarker
Before entering the text, let's take a look at FreeMarker briefly and quickly.
(Friends who have worked in Web development must be quite familiar with FreeMarker. At that time, Mr. Lu was also the first to contact FreeMarker during Web development)
1. Overview: FreeMarker is a template engine. It is a common tool for generating output text based on templates. More is used to design and generate HTML pages.

In short, FreeMarker uses a template to generate a text page to present prepared data. As stated

FreeMarker Official Website: http://freemarker.org/

2. A simple example shows how to use FreeMarker to define a template, bind model data, and generate an Html page that is finally displayed:
1>. Create a project and create a template folder under the project root directory to store our Template file,

For example, the content of the new template file test. ftl is as follows:

 

 Welcome $ {user} <# if user = Big Joe>, our beloved leader ! 

Our latest product :$ {latestProduct. name }!

 

2>. Project Introduction freemarker. jar (: https://jarfiles.pandaidea.com/freemarker.html ),
Use the FreeMarker API method in the Java class to reference the template file, create a data model, merge the data model and the final input of the template file,

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, set it to a file directory cfg. setDirectoryForTemplateLoading (new File (. /template); cfg. setObjectWrapper (new DefaultObjectWrapper (); // obtain or create a Template template Template = cfg. getTemplate (test. ftl); // create the data model Map root = new HashMap (); root. put (user, Big Joe); Map latest = new HashMap (); root. put (latestProduct, latest); latest. put (url, http://blog.csdn.net/janice0529/article/details/products/greenmouse.html); latest. put (name, green mouse); // combines the template and data model and outputs it to lelewriter out = new OutputStreamWriter (System. out); template. process (root, out); out. flush ();} catch (IOException e) {e. printStackTrace ();} catch (TemplateException e) {e. printStackTrace ();}}}

 

3>. The final HTML page code is as follows:

 

 Welcome Big Joe, our beloved leader! 

Our latest product: green mouse!


 

Iii. How to Use FreeMerker to automatically generate Java class code
In the above example, the ftl template file defines an HTML page template, So we define the ftl template as a Java code. By binding the data template, we cannot generate a Java class,
The following section describes how to use templates to automatically create java classes for object objects (it is relatively simple to compile template files for object classes, but simple to simple. The most important thing is to grasp its ideas)
1. PropertyType. java

/*** Property type enumeration class * @ author lvzb.software@qq.com **/public enum PropertyType {Byte, Short, Int, Long, Boolean, Float, Double, String, ByteArray, Date}
2. Property. java
/*** @ * @ Author lvzb.software@qq.com **/public class Property {// attribute data type private String javaType; // attribute 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. java
Import java. util. list;/*** Entity class ** @ author lvzb.software@qq.com **/public class Entity {// package name of the Entity private String javaPackage; // Entity class name private String className; // parent class name private String superclass; // List of Attribute Sets
 
  
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
  
   
GetProperties () {return properties;} public void setProperties (List
   
    
Properties) {this. properties = properties;} public boolean isConstructors () {return constructors;} public void setConstructors (boolean constructors) {this. constructors = constructors ;}}
   
  
 
4. Create a template folder under the project root directory to store our Template file. The content of the newly created entity template entity. ftl is as follows:
package ${entity.javaPackage};/** * This code is generated by FreeMarker * @author lvzb.software@qq.com * */public class ${entity.className}<#if entity.superclass?has_content> extends ${entity.superclass} 
 {    /********** attribute ***********/<#list entity.properties as property>    private ${property.javaType} ${property.propertyName};    
     /********** constructors ***********/<#if entity.constructors>    public ${entity.className}() {        }    public ${entity.className}(<#list entity.properties as property>${property.javaType} ${property.propertyName}<#if property_has_next>, 
 
 ) {    <#list entity.properties as property>        this.${property.propertyName} = ${property.propertyName};    
     }
     /********** 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.${property.propertyName} = ${property.propertyName};    }    
 }
5. automatically generate entity 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;/*** automatically generate entity class client * @ author lvzb.software@qq.com */public class EntityGeneratorClient {private static File javaFile = null; public static void main (String [] args) {Configuration cfg = new Configuration (); try {// Step 1: Specify the data source from which the template file is loaded. Here, a file directory cfg is set. setDirectoryForTemplateLoading (new File (. /template); cfg. setObjectWrapper (new DefaultObjectWrapper (); // Step 2: Obtain the Template file template = cfg. getTemplate (entity. ftl); // Step 3: create a data model Map
 
  
Root = createDataModel (); // Step 4: Merge the template and data model // create a. java 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 the 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 a data model * @ return */private static Map
  
   
CreateDataModel () {Map
   
    
Root = new HashMap
    
     
(); Entity user = new Entity (); user. setJavaPackage (com. study. entity); // create the package name user. setClassName (User); // create a class name user. setConstructors (true); // whether to create a constructor // user. setSuperclass (person); List
     
      
PropertyList = new ArrayList
      
        (); // Create an object Property: Property attribute1 = new Property (); attribute1.setJavaType (String); attribute1.setPropertyName (name); attribute1.setPropertyType (PropertyType. string); // create object attribute 2 Property attribute2 = new Property (); attribute2.setJavaType (int); attribute2.setPropertyName (age); attribute2.setPropertyType (PropertyType. int); propertyList. add (attribute1); propertyList. add (attribute2); // add the attribute set to the object user. setProp Erties (propertyList); // create. java class File outDirFile = new File (./src-template); if (! 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 generate File path * @ param javaPackage java package name * @ param javaClassName java class name * @ return */private static File toJavaFilename (File outDirFile, string javaPackage, String javaClassName) {String pack AgeSubPath = 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. The src-template folder and the automatically generated object class User. java will be generated under the root directory of the project.
As follows:
--- After running --->

 

<Directory structure before running the program> <directory structure after running the program>

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

package com.study.entity;/** * This code is generated by FreeMarker * @author lvzb.software@qq.com * */public class User{    /********** attribute ***********/    private String name;        private int age;        /********** constructors ***********/    public User() {        }    public User(String name, int age) {        this.name = name;        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 age) {        this.age = age;    }    }

 

 

Iv. Thoughts

The above two simple examples show that the so-called automatically generated code is actually:

1. Define the java class template file 2. Define the template data 3. reference the template file (. ftl) and the template data to combine to generate a Java class.

In the above example, some friends may ask if they want to write an object? Why is it so troublesome. the ftl file and the process of writing so many types of data and defining template data are also so troublesome. It is better for me to manually write, declare several attributes, and compile the set/get shortcut keys. Is that true?
Consider from an auxiliary tool and software architecture, and assume that a development auxiliary tool or plug-in is used to automatically generate the entity class and corresponding DAO class. Assume that you need to create 10 entity classes and corresponding DAO classes that contain add, delete, modify, and query basic operations. On the C/S client, I enter the package name, class name, attribute field, and other information, and then generate the package with one click, think about how nice and fun it is (the premise is that your template class is very powerful and universal ), and you may be still pressing Ctrl + C, Ctrl + V.

V. Others
For how to compile the. ftl template file, you need to read the documents and learn by yourself!

 

 

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.