[Turn]java annotations and apt technology

Source: Internet
Author: User
Tags modifier

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&LT; 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

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.