Here is a simple custom note of chestnuts:
package Annotation import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Animal Name Annotated * */ @Target (Elementtype.field) @Retention (retentionpolicy.runtime) @Documented public @interface animalname {String value () default ";}
The annotations are defined, and when needed, the relevant classes, class attributes, annotated information, if there is no response to the annotated message processing process, the annotations can be said to be of no practical value, the next introduction is the Java APT (Annotation process Tool) technology, for the processing of custom annotations.
2,APT Technology
APT (Annotation process Tool), is a code compile time processing annotations, according to certain rules, generate the corresponding Java files, more for the processing of custom annotations, the current more popular Dagger2, Butterknife, EventBus3 are all based on apt technology and have little impact on the performance of the runtime. We'll look at how to use apt by customizing annotations:
1, custom annotations:
@Target({ElementType.TYPE}) ---作用范围 Class@Retention(RetentionPolicy.CLASS) ---生命周期:仅保留到.class文件public @interface Route { /** Path of route*/ String value(); ---类似于成员变量}
2, how to use
@Route(path = "/test/activity2")public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test2); }}
The JVM will only handle annotations that come with languages such as @override by default, and for custom annotations we need to handle them ourselves. Java provides an abstract class called Abstractprocessor.java, and as long as we inherit the class, we implement our own annotation processor to handle the custom @route annotations.
PublicClassRouteprocessorExtendsAbstractprocessor {@OverridePublicsynchronized void init (processingenvironment env) { //Primary initialization action} @Override public Boolean process (set< extends typeelement> annoations, roundenvironment env) { //The logic of the specific processing annotations, control code generation Processannotations (); } @Override public set<string> getsupportedannotationtypes () { //type of annotations supported for processing, here is @route} @Override public sourceversion getsupportedsourceversion () { //java version: Jdk1.6or jdk1.7}}
3, custom processor
@AutoService (Processor.class)PublicClassHelloprocessorExtendsAbstractprocessor {/** file related helper classes are used to generate new source files, class, etc. */Private Filer Mfiler;@OverridePublicSynchronizedvoidInit (processingenvironment processingenv) {Super.init (PROCESSINGENV); Mfiler = Processingenv.getfiler (); }@OverridePublicBooleanProcess (SET< extends typeelement> annotations, roundenvironment roundenv) {The build method is used here in square Company's Javapoet library, which is used to assist in generating the code for the class Methodspec.builder MethodBuilder = Methodspec.methodbuilder ("Show"). Addmodifiers (Modifier.public); Methodbuilder.addstatement ("String test = \" $N \ "","Hello annotation world!");/** Build class */TypeSpec Finderclass = Typespec.classbuilder ("Hello$ $Inject"). Addmodifiers (Modifier.public). Addmethod (Methodbuilder.build ()). build ();try {javafile.builder ( "Com.win.test", Finderclass). Build (). WriteTo (Mfiler); } catch (IOException e) {e.printstacktrace ();} return true;} //supported annotation types @Override public set<string> getsupportedannotationtypes () {set<string> types = new linkedhashset<> (); Types.add (Hello.class.getCanonicalName ()); return types;} @Override public sourceversion Getsupportedsourceversion () {return Super.getsupportedsourceversion (); }}
Used in the AS Project
@Hello("MainTest") //自定义的Hello注解public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }}
In the build directory of the Project app module, the corresponding Java class file is generated:
This is just a simple chestnut, and we can add more business logic in the process () method to achieve a specific function.
[Turn]java annotations and apt technology