Javapoet Source Code Analysis

Source: Internet
Author: User
Tags emit modifier modifiers

Javapoet: is an open source API for generating. Java source files

Github:https://github.com/square/javapoet

To generate a Hellowrold.java file, for example:

1  Package Com.example.helloworld; 2 3  Public Final class HelloWorld {4    Public Static void Main (string[] args) {5     System.out.println ("Hello, javapoet!" ); 6   }7 }
1MethodSpec main = Methodspec.methodbuilder ("main")2 . Addmodifiers (Modifier.public, modifier.static)3. Returns (void.class)4. Addparameter (string[].class, "args")5. Addstatement ("$T. Out.println ($S)", System.class, "Hello, javapoet!")6 . Build ();7 8TypeSpec HelloWorld = Typespec.classbuilder ("HelloWorld")9 . Addmodifiers (Modifier.public, modifier.final)Ten . Addmethod (Main) One . Build (); A  -Javafile javafile = Javafile.builder ("Com.example.helloworld", HelloWorld) - . Build (); the  - ///javafile.writeto (System.out); //System.out Print to the console -  //generate a Java file in User.dir -String directory = system.getproperty ("User.dir");
File File =NewFile (Directory + SEPARATOR + "Hellowrold.java")); APrintStream PS =NewPrintStream (Newfileoutputstream (file)); at Javafile.writeto (PS); - Ps.flush (); -Ps.close ();

In this example, there are three classes of objects: Javafile MethodSpec TypeSpec, first of all see the first javafile

1   Public Static Builder Builder (String PackageName, TypeSpec TypeSpec) {2     checknotnull (PackageName, " PackageName = = null "); 3     Checknotnull (TypeSpec, "typeSpec = = null"); 4     return New Builder (PackageName, typeSpec); 5   }

Builder is a static inner class in Javafile, so you can see that Javapoet is using the builder design pattern. Generate a Builder object from PackageName and TypeSpec, and then call the build method of the builder class:

1  Public Javafile Build () {2       return New Javafile (this); 3     }

Returns the current Javafile object, and then calls the WriteTo method to write the object to the stream/file.

Next look at what TypeSpec is used to construct the builder method.

Staticblock:a generated class, interface, or enum declaration: the Declaration of the class, interface, or enumeration to be generated. is to define the class interface or enumeration, define the time you need to give them a name, add the permission modifier whether the static abstract is final, add methods and other operations

So there are static methods in this class Classbuilder Interfacebuilder EnumBuilder and anonymous inner class Anonymousclassbuilder, all of which return a corresponding builder object

The Builder object is a static inner class in TypeSpec that is used to build the current TypeSpec object. In internal class builder there should be actions such as adding permission modifiers/annotations/annotations/variables to build a class or interface enumeration

Methodspec:a generated constructor or method declaration. The declaration of a method, including the constructor method. So this class has MethodBuilder ConstructorBuilder, which returns a builder object for that class, which is also a static inner class for that class. And this builder internal class also includes the addition of permission modifiers/comments/annotations and other methods, and the method has a return value, parameter Comment statement to build a method

The same principle,Fieldspec is the declaration of the member variable, and there is a builder static inner class that can return the current object, in this builder there is also the addition of annotations annotated access modifiers, and so on, to build a variable.

Class variables have been defined, and then we analyze how to generate Java files, back to the Javafile WriteTo method

There are many overloaded WriteTo methods that will eventually call

1   Public voidWriteTo (appendable out)throwsIOException {2     //First Pass:emit the entire class, just to collect the types we'll need to import.3Codewriter Importscollector =NewCodewriter (null_appendable, indent, staticimports);4 emit (importscollector);5map<string, classname> suggestedimports =importscollector.suggestedimports ();6 7     //Second pass:write The code, taking advantage of the imports.8Codewriter Codewriter =NewCodewriter (out, indent, suggestedimports, staticimports);9 emit (codewriter);Ten}
What is Codewriter? Codewriter converts javafile into strings for use by humans and Javac, implementing import, indentation, and deferred variable names.

Take Fieldspec as an example to illustrate the use of Codewriter:

1 voidEmit (Codewriter codewriter, set<modifier> implicitmodifiers)throwsIOException {2 Codewriter.emitjavadoc (Javadoc);3Codewriter.emitannotations (Annotations,false);4 codewriter.emitmodifiers (modifiers, implicitmodifiers);5Codewriter.emit ("$T $L", type, name);6     if(!Initializer.isempty ()) {7Codewriter.emit ("=");8 Codewriter.emit (initializer);9     }TenCodewriter.emit ("; \ n")); One}

This code is called when a variable is generated. The second line is to write the Javadoc comment, the third line is to write the annotation, the fourth line is the write access modifier, the fifth line is to write the variable's type and variable name, 第6-9 line is to determine whether the variable has an initialization value, if there is a write initialization value

The 10th line is written on behalf of the variable. At this point, the generation process of Helloworld.java is finished.

Some of the methods used in the collection classes:

Collections. Singletonlist

Collections. Emptylist ()

Enumset. CopyOf (set<modifier> modifiers)

Collections. Unmodifiablelist (new arraylist<> (collection)); Returns a non-modifiable view of the specified list. This method allows the module to provide users with "read-only" access to the internal list.

Javapoet Source Code Analysis

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.