introduce
Javapoet is the Java API used to generate. Java source files.
Source file generation can be useful when handling such as annotation processing or interacting with metadata files (for example, database schema, protocol format). By generating code, you eliminate the need to write boilerplate files, while retaining a single source of metadata.
integrated into the project
<!--Https://mvnrepository.com/artifact/com.squareup/javapoet-->
<dependency>
<groupid >com.squareup</groupId>
<artifactId>javapoet</artifactId>
<version>1.11.0 </version>
</dependency>
code Generation class
Generate class
TypeSpec helloworld=typespec.classbuilder ("HelloWorld")
. Build ();
Java files generate
javafile javafile=javafile.builder ("Com.itcast.lyc", HelloWorld). Build ();
try {
//write the contents of the file to the window print out
javafile.writeto (System.out);
} catch (IOException e) {
e.printstacktrace ();
}
The generated content is as follows:
Package COM.ITCAST.LYC;
Class HelloWorld {
}
Method
an Ordinary method
Generate class constructor
Typespec.builder helloworldbuilder=typespec.classbuilder ("HelloWorld");
MethodSpec Main=methodspec.methodbuilder ("main")//Method constructor
. Addparameter (String[].class, "args") Add parameters
. Returns (Void.class)//Add the return value
. addstatement ("$T. Out.println ($S)", System.class, "HelloWorld")/Add content
. Addstatement ("$T. Out.println ($L)", system.class,100l)//Display characters
. build ();
TypeSpec Helloworld=helloworldbuilder.addmethod (Main). build ();
Java files generate
javafile javafile=javafile.builder ("Com.itcast.lyc", HelloWorld). Build ();
try {
//write the contents of the file to the window print out
javafile.writeto (System.out);
} catch (IOException e) {
E.printstacktrace ();
}
where $t represents the. Class class of the class, which can be automatically imported using $t and adddstatement matching, $S represents the injected string, the adddstatement of a injected string-formatted syntax that automatically adds semicolons and line breaks to the statement, plus a number type.
The generated code is as follows:
Package COM.ITCAST.LYC;
Import java.lang.String;
Import Java.lang.System;
Class HelloWorld {
void main (string[] args) {
System.out.println ("HelloWorld");
System.out.println (MB);
}
Method of adding code is also . Addcode ("asdasds;\n"), but. Addcode does not automatically have a component number and a line break, so it is not necessary to write . Addcode (Codeblock.builder (). Addstatement ("$S", "|sdsad"). Build (). Control Flow Javapoet provides us with a convenient API for generating control flow, for example, we want to generate the following:
if (true) {
System.out.println ("OK");
}
It's hard to imagine that if we let ourselves print the trouble of {} parentheses, Javapoet provides Begincontrolflow and Endcontrolflow in the method builder.
MethodSpec Main=methodspec.methodbuilder ("main")//Method constructor
. Addparameter (String[].class, "args") Add parameters
. Returns (Void.class)//Add the return value
. addstatement ("$T. Out.println ($S)", System.class, "HelloWorld")/Add content
. Addstatement ("$T. Out.println ($L)", system.class,100l)//Display characters
. Begincontrolflow ("if (true)")//control flow begins
. Addstatement ("$T. Out.println ($S)", System.class, "OK")
. Endcontrolflow ()//end of control flow
. Build ();
Abstract class
MethodSpec abstractmethon=methodspec.methodbuilder ("Testabs")
. Addmodifiers (Modifier.public, modifier.abstract)
. Build ();
TypeSpec Typespec=typespec.classbuilder ("Testabs")
. Addmodifiers (modifier.public,modifier.abstract)
. Addmethod (Abstractmethon)
. Build ();
Interface Class
MethodSpec abstractmethon=methodspec.methodbuilder ("Testinterfaces")
. Addmodifiers (Modifier.PUBLIC, modifier.abstract)
. Build ();
TypeSpec Typespec=typespec.interfacebuilder ("Testinterfaces")
. Addmodifiers (Modifier.public)
. AddField ( Fieldspec.builder (String.class, "only_once")
. Addmodifiers (modifier.public,modifier.static,modifier.final)
. Initializer ("$S", "OKKK")
. Build ())
//Add fields
. Addmethod (Abstractmethon)
. Build ();
Construction Method
The construction method
MethodSpec consructormethod=methodspec.constructorbuilder ()
. Addmodifiers (modifier.public)
. Addparameter (Integer.class, "age")//Parameter
. Addstatement ("this. $N = $N", "Age", "age")//Add style code $n represents a reference to the current class
. Build ();
TypeSpec helloworld= helloworldbuilder
. Addmethod (Main)//Add Main method
. AddField (Fieldspec.builder ( Integer.class, ' age '). Addmodifiers (Modifier.private). Build ())//Add field
. Addmethod (Consructormethod)//Add construction method
. Build ();
Add Parameters
. Addparameter (Integer.class, "age")//Parameter
Parameterizedtypename Parameterizedtypenamemap=parameterizedtypename.get (
classname.get (Map.class),
Classname.get (Integer.class),
parameterizedtypename.get (
classname.get (class.class),
Wildcardtypename.subtypeof (Classname.get (Object.class))
)
;
Parameterizedtypename Parameterizedtypenamelist=parameterizedtypename.get (
classname.get (List.class),
Wildcardtypename.subtypeof (Classname.get (Integer.class))
);
Add a method with parameters
MethodSpec parmmethod=methodspec.methodbuilder ("welomebeijing")
. Addparameter (String.class , "Parm")
. Addparameter (Parameterspec.builder (Parameterizedtypenamemap, "map"). Build ())
. Addparameter ( Parameterspec.builder (parameterizedtypenamelist, "List"). Build ())
.
Final Build Effect:
void Welomebeijing (String parm, Map<integer, class<?>> Map, list<? extends integer> List) {
}
Parameters that need to generate wildcard characters are used
. Addparameter (Parameterspec.builder (Typevariablename.get ("T"), "T"). Build ())
The following refers to other people's diagram to deepen understanding: Click to open the link
Add Field
. AddField (Fieldspec.builder (Integer.class, "age"). Addmodifiers (Modifier.private). Build ())//Add Field
Enums
File File=new file (System.getproperty ("User.dir"), "\\src\\main\\java"); TypeSpec Typespec=typespec.enumbuilder ("Enumstest"). Addmodifiers (modifier.public). Addenu Mconstant ("Rock", Typespec.anonymousclassbuilder ("$S", "Page"). Addmethod (Methodspec.methodbuild ER ("toString"). Addannotation (Override.class). Add
Modifiers (modifier.public). Addstatement ("Return $S", "avalanche")
. Returns (String.class). Build (). Build ()) . Addenumconstant ("Sci", Typespec.anonymousclassbuilder ("$S", "ssss"). Build ()). Addenumconstant ( "Apple", Typespec.anonymousclassbuilder ("$S", "sad"). Build ()). AddField (String.class, "Hand", modifier.private , modifier.final). Addmethod (methodspec.constructOrbuilder (). Addparameter (String.class, "Hand"). Addstatement ("this. $N =
$N "," Hand "," hand "). Build ().
Javafile Javafile=javafile.builder ("Com.itcast.lyc.javapoet", TypeSpec). Build (); Javafile.writeto (file);
Generate Code:
Package Com.itcast.lyc.javapoet;
Import Java.lang.Override;
Import java.lang.String;
Public enum Enumstest {rock
(' Page ') {
@Override public
String toString () {return
' avalanche ';
}
,
Sci ("SSSs"),
Apple ("sad");
Private final String hand;
Enumstest (String hand) {
This.hand=hand
}}
Enumeration types Add enumeration classes through the Typespec.enumbuilder constructor.
Inner class
TypeSpec comparator = Typespec.anonymousclassbuilder ("")
. Addsuperinterface (Parameterizedtypename.get ( Comparator.class, String.class))
. Addmethod (Methodspec.methodbuilder ("compare")
. Addannotation ( Override.class)
. Addmodifiers (modifier.public).
Addparameter (String.class, "a")
. Addparameter ( String.class, "B")
. Returns (Int.class).
addstatement ("return $N. Length ()-$N. Length ()", "A", "B")
. Build ())
.
TypeSpec HelloWorld = Typespec.classbuilder ("HelloWorld")
. Addmethod (Methodspec.methodbuilder ("Sortbylength") )
. Addparameter (Parameterizedtypename.get (List.class, String.class), "strings")
. Addstatement ("$T. Sort ($N, $L) ", Collections.class," strings ", comparator)
. Build ()
.
Get Java code
void Sortbylength (list<string> strings) {
Collections.sort (strings, new comparator<string> () {
@ Override public
int Compare (string A, string b) {return
a.length ()-b.length ();
}
});
The inner class construct initializes the inner class with the inner class construction method Typespec.anonymousclassbuilder (""), and then uses the reference to the inner class.
Add a comment
Fields, methods, classes can all add comments
MethodSpec dismiss = Methodspec.methodbuilder ("Dismiss")
. Addjavadoc ("Hides {@code message} from the caller" s History. other\n "
+" participants in the conversation'll continue to = the\n "+" message in their own history-unless
th EY also delete it.\n ")
. Addjavadoc (" \ n ")
. Addjavadoc (" <p>use {@link #delete ($T)} to delete the entire\n " c5/>+ "Conversation for All participants.\n", Conversation.class)
. Addmodifiers (Modifier.public, modifier.abstract)
. Addparameter (Message.class, "message")-build
();
Effect
/**
* Hides {@code message} from the caller ' s history. The other * Participants in the conversation would continue to the "* message" in their-own history unless they
als o delete it.
*
* <p>use {@link #delete (conversation)} to delete the entire
* conversation for all participants.
* *
void Dismiss (message message);
Use $t to reference classes.
Add Annotations
Add annotations using Annotationspec.builder ():
MethodSpec LogRecord = Methodspec.methodbuilder ("RecordEvent")
. Addmodifiers (Modifier.public, modifier.abstract)
. Addannotation (Annotationspec.builder (Headers.class)
. AddMember ("Accept", "$S", " Application/json; Charset=utf-8 ")
. AddMember (" useragent "," $S "," Square Cash "). Build
())
. Addparameter (Logrecord.class, "LogRecord")
. Returns (Logreceipt.class)
. Build ();
Effect
@Headers (
accept = "Application/json; Charset=utf-8 ",
useragent =" Square Cash "
)
logreceipt recordevent (LogRecord LogRecord);