[Source] topic of java custom annotation notes Quest and achieve

In java, notes should appear as the most magic, and used judiciously can make the code more elegant. Usually have been addicted to convenience comment brought us in, knowing only, but not in-depth understanding of its principles and implementation, Benpian on with everyone in the Quest jdk notes.

A. The concept notes

Java provides the ways and means any information and any associated metadata of one element of the original program. Personal understanding is: annotation allows you to more easily associated with any classes, methods, elemental sounds like or do not understand well, it does not matter, continue to look down, basically completing custom annotation understanding of the annotation is more clear. .

Two .jdk own notes

Notes from jdk1.5 began to emerge, jdk own notes, there are three common, they should also not strange that the three notes are: @ Override, @ Deprecated, @ SuppressWarnings.

@Override: one of the most appear, or subclass overrides the parent class when used in rewrite.

@Deprecated: deprecated meaning of the word is deprecated, see the name to know Italian, this annotation is mainly used when using a deprecated method, which means that this method may be outdated, but for compatibility with the code of the system is still reservations can also be used, but not recommended, you can find a large number of such notes in Jdk source, some method of operation of such date date class in the package, it is worth noting that once added the comment, the compiler method strikethrough appears when Lane called.

@SuppressWarnings: suppress suppression is the meaning of this annotation means that close to improper compiler warnings, forcing the compiler to suppress warning out, with very little, almost no how come across, if you have the code over the top, can fit @SuppressWarnings comment when called with @Deprecated annotation methods, can be masked warning from the compiler.

III. Custom annotation

Custom annotation is a feature very powerful, clever use not only allows you to reduce the amount of code development, but also allow your code is full of "forced cell."

Before learning custom annotation, first to learn the next four kinds of yuan notes, because implementation of a custom annotation by means of them.

Meta-annotation is jdk notes provided by her four yuan notes are:

@Target: After using the annotation, annotation can be specified from the definition of what may be used, particularly by ElementType specified therein.

@Documented: After using the annotation, the annotation will be customized to generate the javadoc.

@Retention: period specified annotations are retained, as specified in RetentionPolicy in general are RUNTIME.

@Inhertried: Allow annotation subclass inherits the parent class of the added comment table Hinako annotation class can inherit the parent class, but only on the class annotation applied active, inactive, on the method.

 

@Target

This annotation can be used to indicate where possible ElementType parameters are:

CONSTRUCTOR: constructor declaration

FIELD: field declaration (including enum example)

LOCAL_VARIABLE: local variable declaration

METHOD: the method declaration

PACKAGE: package declaration

PARAMETER: parameter declarations

TYPE: class, interface (including type of annotation), or an enum declaration

@Retention

He expressed the need to save the annotation information at what level. RetentionPolicy optional parameters include:

SOURCE: Notes will be discarded compiler

CLASS: Annotations can be used in the class file, but will be dropped VM

RUNTIME: VM will remain during operation annotations, annotation information can be read by reflection.

@Documented

The notes contained in the Javadoc

@Inherited

It allows annotation subclass inherits the parent class

 

Learn yuan finished four kinds of notes, we will look at practical operation, a comment from a set play.

FIG custom annotation format:

Custom annotation format shall be as this is jdk develop, so do not even think about myself ... I set up a custom annotation @Man, indicating that the comment only on the field, and is retained during operation .

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Man {
    String sex() default "男";
}

Then we can test it by reflecting the annotation, first create a class Person, coupled with the comment in its field, and then we see if in force:

public class Person {
    @Man
    public String sex;
}
public class Test {
    public static void main(String[] args) {
        Class clzz = Person.class;
        try {
           Field field = clzz.getField("sex");
            System.out.println(field.getAnnotation(Man.class).sex());
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}

Annotations can be seen already in force, at first glance nothing seems too much custom annotation with, but in fact, if you think my brain can only show you the hole is not big enough, rich enough imagination.

In the actual development, there are many scenes custom annotation can play the power, such as we are familiar with hibernate, jpa, mybatis and so on, we should be used @TableFiled (value = "xxx") This comment is based on a custom annotations to achieve. another example is if you make a permission to develop very complex system, which has a multi-level authority, not only each level has different access interface, interface to see the contents are not the same, involving the jurisdiction of the area, so it had a more complex development authority, if the conventional way to solve can be tricky, but if you use a custom annotation + AOP, the problem becomes relatively easy:

AOP unified interception, then according to the list of permissions to determine the value of notes owned, then the authority to intercept the content area of ​​the interface according to the parameters of the request, the problem is solved and did not invade the existing code, only need to add the comment in the original Interface , next only say perfect for this elegant mode of operation!

There is also a magical effect, is today just GET from there to other people, that is the custom annotation can also add notes @Component, your customized annotations to srping container to manage, and then you can use the following this ways to get the notes labeled with your custom class.

/ Ctx is a Spring ApplicationContext //

Bean Map<String, Object> myAnnotationBeanMap = ctx.getBeansWithAnnotation(Man.class);

This can make for some special classes Bean operating after initialization.

Published 89 original articles · won praise 70 · views 40000 +

Guess you like

Origin blog.csdn.net/lovexiaotaozi/article/details/88351750