"Java Basics" Java Annotations "@" Detailed

Java annotations meaning:

Java annotations, by definition, annotations, is a thing to add explanatory notes, will store some information that may be of a later period of time is very useful.
Java annotations label called java, java provides a mechanism so that we can add to the standard methods, classes, parameters, packages, domains and variables (ie attach certain information). After a certain period, and the extracted information marked for use by reflection.

 

Sample (a realization of their own notes):

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(value = {ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotaion {
    String value();
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(value = {ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyFieldAnnotaion {
    String value();
    String type();
    String lengths();
}
import java.io.Serializable;

@MyAnnotaion("student")
public class Student implements Serializable {

    private static final long serialVersionUID = 1L;

    @MyFieldAnnotaion(value = "1",type = "int",lengths = "10")
    String id;
    @MyFieldAnnotaion(value = "蕾蕾",type = "String" ,lengths = "200")
    String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}
Import org.apache.poi.ss.formula.functions.T; 

Import java.lang.annotation.Annotation;
 Import as java.lang.reflect.Field; 

/ ** 
 * obtained by reflecting annotations 
 * / 
public  class AnnotaionDemo {
     public  static  void main (String [] args) throws Exception { 
        Class <T> = clazz (Class <T>) the Class.forName ( "demo.knowledgepoints.annotation.Student" );
         // determines whether there is a comment 
        iF (clazz.isAnnotationPresent (MyAnnotaion . class )) { 
            System.out.println ( "comments exist: MyAnnotaion" ); 
        }

        // Get a list of annotations 
        the Annotation [] = annotaions clazz.getAnnotations ();
         for ( int I = 0; I <annotaions.length; I ++ ) { 
            System.out.println ( "comment:" + annotaions [I]); 
        } 

        // Get annotations and 
        myAnnotaion myAnnotaion = clazz.getAnnotation (myAnnotaion. class ); 
        System.out.println ( "annotation is:" + myAnnotaion.value ()); 

        // Get the annotations and method 
        Field field = clazz .getDeclaredField ( "the above mentioned id" ); 

        // comment on whether there is a method 
        field.isAnnotationPresent (MyFieldAnnotaion. class );
        // method annotated list 
        field.getAnnotations (); 

        // get comment on the contents of the method 
        MyFieldAnnotaion myFieldAnnotaion = field.getAnnotation (MyFieldAnnotaion. Class ); 
        System.out.println ( "value:" + myFieldAnnotaion.value () + "; type: "myFieldAnnotaion.type + () +"; lengths: "+ myFieldAnnotaion.lengths ()); 
    } 
}

operation result:

According to this case:

1. Notes implementation requires Keywords: @interface;

2. On the notes We also use the annotation @ Target, @ Retention. These are called meta-annotation,

   Zhongyuan Java Annotations are four: @Retention @Target @Document @Inherited;

   @Retention: annotation reserved position

        @Retention (RetentionPolicy.SOURCE) // annotation exists only in source code, is not included in the class bytecode files

     @Retention (RetentionPolicy.CLASS) // default retention policy, annotations exist in the class bytecode file, but the runtime is not available,

     @Retention (RetentionPolicy.RUNTIME) // annotations exist in the class bytecode files, can be obtained by reflection at runtime

    @Target: the role of the target annotation

        @Target (ElementType.TYPE) // interfaces, classes, enumerations

        @Target (ElementType.FIELD) // field, enumeration constants

        @Target(ElementType.METHOD) //方法

        @Target (ElementType.PARAMETER) // method parameters

        @Target (ElementType.CONSTRUCTOR) // Constructor

        @Target (ElementType.LOCAL_VARIABLE) // local variables

        @Target(ElementType.ANNOTATION_TYPE)//注解

        @Target(ElementType.PACKAGE) ///包

    @Document: indicates that the annotation will be included in the javadoc

    @Inherited: Description subclass can inherit the parent class notes

3. Direct methods which can be written: String value (); 

   Use external annotation value may be written to, you can get the value subsequent use.

You can provide default values: String value () default "flower";   

 

AnnotaionDemo implemented method modifying a common function, annotation by the value of the injected entity classes: 

import org.apache.poi.ss.formula.functions.T;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 通过反射获取注解
 */
public class AnnotaionDemo {
    public static void main(String[] args) throws Exception {
        Student student = (Student) getbean("demo.knowledgepoints.annotation.Student");
        System.out.println(student);
    }

    public static Object getbean(String className) throws Exception{
        Class<T> clazz = (Class<T>) The Class.forName (className);
         // determines whether there annotations (the annotations are used as labeled) 
        IF (clazz.isAnnotationPresent (MyAnnotaion!. Class )) {
             the throw  new new Exception ( "missing class notes" MyAnnotaion ", can not be Get reflecting the bean " ); 
        } 

        // Create entity class 
        Object Object = clazz.newInstance (); 

        Field, [] Fields = clazz.getDeclaredFields ();
         for ( int I = 0; I <fields.length; I ++ ) {
             // field name Get 
            String name = fields [I] .getName (); 

            // filtered sequence 
            if (name.equals("serialVersionUID")) {
                continue;
            }

            //组装SET方法
            Class<?> type = clazz.getDeclaredField(name).getType();

            // 首字母大写
            String replace = name.substring(0, 1).toUpperCase()
                    + name.substring(1);
            Method setMethod = clazz.getMethod("set" + replace, type);
            //获取字段值
            Field field = clazz.getDeclaredField(name);
            MyFieldAnnotaion myFieldAnnotaion = field.getAnnotation(MyFieldAnnotaion.class);
            Value String = myFieldAnnotaion.value ();
             // set method was executed 
            IF (! = Value null ! && "" .equals (value)) {
                 // --- determine the type of the read data (type determination portion) 
                IF (type .isAssignableFrom (String. class )) { 
                    setMethod.invoke (Object, value); 
                } the else  IF (type.isAssignableFrom ( int . class )
                         || type.isAssignableFrom (Integer. class )) { 
                    setMethod.invoke (Object, Integer. the parseInt (value)); 
                }else if (type.isAssignableFrom(Double.class)
                        || type.isAssignableFrom(double.class)) {
                    setMethod.invoke(object, Double.parseDouble(value));
                } else if (type.isAssignableFrom(Boolean.class)
                        || type.isAssignableFrom(boolean.class)) {
                    setMethod.invoke(object, Boolean.parseBoolean(value));
                }
            }
        }
        return object;
    }
}

operation result:

Cases using reflection: reflection Comments: https://www.cnblogs.com/jssj/p/11723910.html

Summary Language: annotation function is widely used in the framework of development: such as Spring, MyBatis and so on. Notes appear greatly reduces the development effort in the development work.

 

 

Guess you like

Origin www.cnblogs.com/jssj/p/11811227.html