[Java] Annotation basis of the nature and custom implementation

The principle of annotations in Java

I. Introduction

Before Java5, use xmlto configure the operation of major conventional framework, this approach can achieve loose coupling and complete framework to configure almost any need, but with the expansion project, xmlthe contents of the file itself will become very complicated, maintenance the cost has risen considerably.

Therefore, it was proposed to use a high-tag-coupled configuration, which may provide a similar mechanism for annotation, to the information or metadata (Metadata) the program elements (classes, methods, member variables, etc.) associated. This association of program elements (classes, methods, member variables) plus a more intuitive explanation, but independent of the program instructions which service logic itself, is designed to provide a particular tool or to a framework.

Second, what is a comment, the essence of what?

In Java annotations are some of the source code of additional information for some of the tools in the compilation, interpretation and use of run-time, play instructions, configuration functions. You can annotate understood as a modifier declaration applies to classes, methods, parameters, variables. Notes code itself does not affect the business logic, can only play a supporting role only sexual.

For a description of the Java Annotation interface has so many words:

It means: This interface is all annotation types are inherited common interface. This sentence may be difficult to understand. With our common @Overridenotes taken as an example, its source code is as follows:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}

The code above to understand our common format, then it should be the following sub-sub:

public interface Override extends Annotation {
    
}

Now you can understand, the so-called notes, by its very nature is an inherited interface Annotation interface only.

As an interface, and if no other implementation class corresponding parsing code words, the effect may not be useful as a comment come.

So when we define a good comment, we need to help the underlying code, annotations will play its due role. Annotation as a special interface, which is the implementation class of the code generated dynamically at runtime proxy class, while after the underlying code annotations acquired by way of reflection, which returns proxy object dynamically generated Java runtime $Proxy. By proxy objects proxy object custom annotation (Interface) method call , it will end up calling AnnotationInvocationHandlerthe invokemethod. This method from memberValuesthe Mapindex of the corresponding value. The memberValuessource of the Java constant pool.

Third, meta-annotation

Since the annotation is essentially just an interface to achieve their specific functions need to help the underlying code, then we know we have to let the underlying code to make this comment to do? Java provides a meta-annotation to help us to solve the problem.

Meta-annotation is provided for Java annotations modification notes for custom annotation.

annotation provided a total of four yuan notes, are:

@Target: notes the role of the target;
@Retention: annotation statement period;
@ Inherited: Indicates whether to allow inherited;
@Documented: whether notes will be included in the JavaDoc;

@Target

@Target the target specified in the modified final notes of the role that used to specify this annotation is used to modify the final method, or modifying class or attribute modification?

@Target source code is shown below:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
    /**
     * Returns an array of the kinds of elements an annotation type
     * can be applied to.
     * @return an array of the kinds of elements an annotation type
     * can be applied to
     */
    ElementType[] value();
}

In the above example @Override source code, then @Target(ElementType.METHOD), as shown by modifying the code of this method it can only be used for annotation, the class can not be used or modified properties. ElementType which is an enumerated type, have the following values to choose from:

Allow comments on a modified role in the classes, interfaces, and enumerations: ElementType.TYPE

ElementType.FIELD: allowed to act on the attribute field

ElementType.METHOD: allowed to act on the method of

ElementType.PARAMETER: allowed to act on the method parameters

ElementType.CONSTRUCTOR: allowed to act on the constructor

ElementType.LOCAL_VARIABLE: allowed to act on the local local variables

ElementType.ANNOTATION_TYPE: allowed to act on the notes

ElementType.PACKAGE: allowed to act on the cladding

@Retation

@Retention annotation indicates that the current life cycle, the source code is as follows:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
    /**
     * Returns the retention policy.
     * @return the retention policy
     */
    RetentionPolicy value();
}

Consistent with the above, the comment also has a property value, this also provides RetentionPolicy enumerated type, which includes the following values:

RetentionPolicy.SOURCE: discarded at compile time. These annotations at the end of the compiler will no longer have any meaning, they do not write byte. @Override, @SuppressWarnings belong to such comments.

RetentionPolicy.CLASS: class loading when discarded. Useful bytecode files. Notes default this way

RetentionPolicy.RUNTIME: are never discarded run also keep the notes, so you can use reflection to read the annotation information. Annotations our custom commonly used in this way.

@Documented & @Inherited

@Documented comment modified comment, when we execute JavaDoc documentation package is saved into doc documents, on the contrary will be discarded when packaging.

@Inherited annotation notes is a modified inheritable, also notes that we modify a class, and that class subclass will automatically inherit the parent class notes.

Fourth, the common Annotation

@Override

java.lang.Override is a marker annotation type, which is used as a labeling method. It illustrates a method is marked overloading of a parent class, the assertion played a role. If we use this annotation in a method of the parent class method does not cover, java compiler warning will be a compilation error.

@Deprecated

Deprecated is a type of marker annotations. When using a type or type member @Deprecated modified, then the compiler will not encourage the use of this program element is marked. Therefore, the use of this modification has a certain "continuity": If we covered through inheritance or in code mode using this obsolete type or member, or members, although the type of inheritance or is not covered after being declared as @Deprecated, but the compiler still reported to the police.

@SuppressWarnings

SuppressWarning not a mark type annotations. It has a type of String [] members, is a member of the banned warning name. For javac compiler is concerned, the option is -Xlint effective warning to @SuppressWarings name is also effective, but the compiler does not recognize ignored warnings name. @SuppressWarnings ( "unchecked")

V. custom annotation

Some rules for writing custom annotation categories:

  1. Annotation type is defined as @interface, all Annotation will automatically inherit java.lang.Annotation this interface, and can not go to inherit another class or interface.
  2. Parameters can only use public or members of the default (default) access to these two modifications
  3. Members can only use the basic parameters of type byte, short, char, int, long, float, double, boolean eight basic data types and String, Enum, Class, annotations and other data types, as well as some types of this array.
  4. For class methods and fields annotation information must be obtained through the Java Annotation objects reflection technology, because in addition you have no other method to get an object annotation
  5. Notes can also define members ,, but did not comment on such a futile
PS:自定义注解需要使用到元注解

Six custom annotation examples

FruitName.java

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * 水果名称注解
 */
@Target(ElementType.FIELD)
@Retention(RUNTIME)
@Documented
public @interface FruitName {
    String value() default "";
}

FruitColor.java

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * 水果颜色注解
 */
@Target(FIELD)
@Retention(RUNTIME)
@Documented
public @interface FruitColor {
    /**
     * 颜色枚举
     */
    public enum Color{ BLUE,RED,GREEN};
    
    /**
     * 颜色属性
     */
    Color fruitColor() default Color.GREEN;

}

FruitProvider.java

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;


/**
 * 水果供应者注解
 */
@Target(FIELD)
@Retention(RUNTIME)
@Documented
public @interface FruitProvider {
    /**
     * 供应商编号
     */
    public int id() default -1;
    
    /**
     * 供应商名称
     */
    public String name() default "";
    
    /**
     * 供应商地址
     */
    public String address() default "";
}

FruitInfoUtil.java

import java.lang.reflect.Field;

/**
 * 注解处理器
 */
public class FruitInfoUtil {
    public static void getFruitInfo(Class<?> clazz){
        
        String strFruitName=" 水果名称:";
        String strFruitColor=" 水果颜色:";
        String strFruitProvicer="供应商信息:";
        
        Field[] fields = clazz.getDeclaredFields();
        
        for(Field field :fields){
            if(field.isAnnotationPresent(FruitName.class)){
                FruitName fruitName = (FruitName) field.getAnnotation(FruitName.class);
                strFruitName=strFruitName+fruitName.value();
                System.out.println(strFruitName);
            }
            else if(field.isAnnotationPresent(FruitColor.class)){
                FruitColor fruitColor= (FruitColor) field.getAnnotation(FruitColor.class);
                strFruitColor=strFruitColor+fruitColor.fruitColor().toString();
                System.out.println(strFruitColor);
            }
            else if(field.isAnnotationPresent(FruitProvider.class)){
                FruitProvider fruitProvider= (FruitProvider) field.getAnnotation(FruitProvider.class);
                strFruitProvicer=" 供应商编号:"+fruitProvider.id()+" 供应商名称:"+fruitProvider.name()+" 供应商地址:"+fruitProvider.address();
                System.out.println(strFruitProvicer);
            }
        }
    }
}

Apple.java

import test.FruitColor.Color;

/**
 * 注解使用
 */
public class Apple {
    
    @FruitName("Apple")
    private String appleName;
    
    @FruitColor(fruitColor=Color.RED)
    private String appleColor;
    
    @FruitProvider(id=1,name="陕西红富士集团",address="陕西省西安市延安路89号红富士大厦")
    private String appleProvider;
    
    public void setAppleColor(String appleColor) {
        this.appleColor = appleColor;
    }
    public String getAppleColor() {
        return appleColor;
    }
    
    public void setAppleName(String appleName) {
        this.appleName = appleName;
    }
    public String getAppleName() {
        return appleName;
    }
    
    public void setAppleProvider(String appleProvider) {
        this.appleProvider = appleProvider;
    }
    public String getAppleProvider() {
        return appleProvider;
    }
    
    public void displayName(){
        System.out.println("水果的名字是:苹果");
    }
}

FruitRun.java

/**
 * 输出结果
 */
public class FruitRun {
    public static void main(String[] args) {
        FruitInfoUtil.getFruitInfo(Apple.class);
    }
}

Operating results are:


Fruits Name: Apple
fruit color: RED
Supplier Code: Supplier Name 1: Shaanxi Fuji Group Supplier Address: Xi'an, Shaanxi Province, Yan'an Road, Building 89 Fuji

VII reference

  • https://www.cnblogs.com/acm-bingzi/p/javaAnnotation.html

If infringement, please contact deleted!

Guess you like

Origin www.cnblogs.com/jojop/p/11327895.html