Java meta Annotations-life cycle @Retention

Source: Internet
Author: User

Java1.5 the introduction of meta-annotations, now the most active open source community spring began to highly respected, originally familiar with the various XML configuration, at a glance, suddenly disappeared, a variety of annotations, configuration readability is seriously threatened. On the other hand, the various cool features of AOP allow developers to use a variety of custom annotations. In the custom meta-annotation @annotation, there are two features that must be defined clearly, one is target (annotation object), the other is retention (the annotation life cycle, also called the Declaration cycle), and today we first recognize the next cycle.

@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface CallerServiceValidator {    String value() default "";    Class<?> validatorClass() default DEFAULT.class;    final class DEFAULT {}}
Meta Annotations life cycle @retention

There are three life cycles of meta-annotations, and enumerations are defined in Retentionpolicy, which are source, class, and runtime respectively.
When customizing meta annotations, the vast majority of developers (unless you're a user of the next two scenarios) are using runtime, which is a good understanding, and we expect to get these annotations when the program runs, and do something interesting, and only Retentionpolic.runtime to ensure that custom annotations remain visible at run time. For example, after the spring project is started, get the definition of all or part of the available interfaces in parallel:

try {String basepath = "";            Requestmapping baserequestmapping = annotationutils.findannotation (Bean.getclass (), RequestMapping.class);            if (baserequestmapping! = null) {BasePath = Stringutils.join (Baserequestmapping.path ());            } method[] methods = Reflectionutils.getalldeclaredmethods (Aoputils.gettargetclass (bean));                if (Methods! = null) {Beanmetas = new copyonwritearraylist<> (); for (Method method:methods) {try {requestmapping methodrequestmapping = Anno                        Tationutils.findannotation (method, Requestmapping.class);                        Apiignore Apiignore = Annotationutils.findannotation (method, Apiignore.class); if (methodrequestmapping! = null && (Apiignore = = NULL | |!apiignore.value ())) {PLATFO Rmapimeta Platformapimeta = new Platformapimeta (Aoputils.gettargetclass (BEAn). GetName (), Method.getname (), BasePath + stringutils.join (Methodrequestmapping.path ()                            ));                            requestmethod[] Httpmethods = Methodrequestmapping.method (); if (httpmethods! = null && httpmethods.length > 0) {string[] Httpmethodarr = NE                                W String[httpmethods.length]; for (int i = 0; i < httpmethods.length; i++) {Requestmethod HttpMethod = HttpMethod                                    S[i];                                Httpmethodarr[i] = Httpmethod.name ();                            } platformapimeta.sethttpmethods (Httpmethodarr);                            } platformapimeta.setmodulename (ModuleName);                            Apioperation apioperation = Annotationutils.findannotation (method, Apioperation.class); if (apioperation! = nulL) {Platformapimeta.setdesc (Apioperation.value ());                            } Collectmethodparamsreturn (Platformapimeta, method, Bean);                        Beanmetas.add (Platformapimeta);                    }} catch (Exception e) {logger.error (Exceptionutils.getstacktrace (e)); }}}} catch (Exception e) {logger.error (Exceptionutils.getstac        Ktrace (e)); }

Retentionpolic.source is rarely used by developers, to cite several Java-brought usage scenarios.

@Target(ElementType.METHOD)@Retention(RetentionPolicy.SOURCE)public @interface Override {}
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})@Retention(RetentionPolicy.SOURCE)public @interface SuppressWarnings {

See, these annotations are only used when compiling, and once the compilation is complete, the runtime doesn't make any sense, so they're called source-level annotations. Developers who have experienced code generation, such as Lombok developers, know that it is automatically generated as part of the code at compile time by annotations, making the source look more concise and bytecode very powerful. Of course, this approach has its own flaws, such as inconsistencies, trouble-solving problems, and dependency issues, which are not discussed here.

For the same reason, althoughRetentionpolic.class is defined as the default period for annotations, it is not the preferred choice for regular developers to customize annotations, CLASS types are more difficult to understand than source and runtime, Because developers usually have no obstacles to pre-compile and run-time understanding, but the compiled bytecode retains the meta-annotations and cannot be used at runtime. Let's look at a spring-boot example.

Springboot for the config Meta Data Processor (CONFIGURATIONMETADATAANNOTATIONPROCESSOR), which is collected through Metacollector, and then Metastore exists meta-inf/ Spring-configuration-metadata.json. We do not discuss why spring to do so, what is the advantage, interested can read the source of their own, at the moment we are concerned about the retentionpolic.class, and the implementation of what is the relationship. Configurationmetadataannotationprocessor implementation of the processor interface, and processor interface, is specifically used to deal with meta-annotations, the name of the annotation processor. The annotation processor can help us do something that sounds strange from the bytecode level, such as information collection, bytecode refactoring, bytecode generation, and so on. If this is really the case, congratulate you, because you've already surpassed most Java developers, at least you know a lot about ASM, the structure definition of classes Classnode, and how to read them cla***eader.

section below:
Source is a source-level annotation that is used only at compile time;
class is a bytecode-level annotation and is mostly used at compile time;
Runtime is our friends and family, the runtime is visible annotations.

Java meta Annotations-life cycle @Retention

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.