java custom annotation and get the value of the annotation

1. User defined annotation

Copy code
import java.lang.annotation.*;

@Documented
@Target(ElementType.FIELD)
@Inherited
@Retention(RetentionPolicy.RUNTIME )
public @interface MyAnno {
/**
*Can it be null
* @return
*/
boolean isCanNull() default true;

/**
 * Can it be an empty string
 * @return
 */
boolean isCanEmpty() default true;

/**
 * Can it be 0
 * @return
 */
boolean isCanZero() default true;

}
Copy code
2. Use notes:

Copy code
public class Mouse {

@MyAnno(isCanNull=true)
private  String name;
@MyAnno(isCanNull = false,isCanZero = false)
private  int age;
@MyAnno(isCanNull = false)
private String address;
@MyAnno(isCanZero = false)
private double money;

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public double getMoney() {
    return money;
}

public void setMoney(double money) {
    this.money = money;
}

public String getName() {
    return name;
}

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

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

}
Copy code
3. Obtain the value of the annotation and judge it

Copy code
package com.vweb.util;

import com.vweb.webapp.Mouse;
import com.vweb.webapp.MyAnno;
import com.vweb.webapp.TestUtil;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

public class IntactCheckUtil {

public static boolean check(Object obj){
       // list = Arrays.asList(AnnotationParsing.class.getClassLoader().loadClass(((Class)obj).getClass().getName()).getDeclaredFields());
    List<Field>  list = Arrays.asList(obj.getClass().getDeclaredFields());
    for(int i=0;i<list.size();i++){
        Field field = list.get(i);
        if(field.isAnnotationPresent(MyAnno.class)){//Use MyAnno annotation
            for (Annotation anno : field.getDeclaredAnnotations()) {//Get all comments
                if(anno.annotationType().equals(MyAnno.class) ){//Find your own annotation
                    if(!((MyAnno)anno).isCanNull()){//Annotation value
                        if(TestUtil.getFieldValueByName(field.getName(),obj)==null){
                            throw new RuntimeException("Class:"+Mouse.class+"Properties of:"+field.getName()+"Cannot be empty, actual value:"+TestUtil.getFieldValueByName(field.getName(),obj)+",Notes: field.getDeclaredAnnotations()");
                        }
                    }
                    if(!((MyAnno)anno).isCanEmpty()){
                        if(TestUtil.getFieldValueByName(field.getName(),obj).equals("")){
                            throw new RuntimeException("Class:"+Mouse.class+"Properties of:"+field.getName()+"Cannot be an empty string, actual value:"+TestUtil.getFieldValueByName(field.getName(),obj)+",Notes: field.getDeclaredAnnotations()");
                        }
                    }
                    if(!((MyAnno)anno).isCanZero()){
                        if(TestUtil.getFieldValueByName(field.getName(),obj).toString().equals("0") || TestUtil.getFieldValueByName(field.getName(),obj).toString().equals("0.0")){
                            throw new RuntimeException("Class:"+Mouse.class+"Properties of:"+field.getName()+"Cannot be null character 0, actual value:"+TestUtil.getFieldValueByName(field.getName(),obj)+",Notes: field.getDeclaredAnnotations()");
                        }
                    }
                }
            }
        }

    }
    return  true;
}

}
Copy code
Note: note the use of various parameters (the following contents are from the Internet) http://www.cnblogs.com/peida/archive/2013/04/24/3036689.html )

@Target:

@Target describes the object scope modified by Annotation: Annotation can be used for packages, types (classes, interfaces, enumerations, Annotation types), type members (methods, construction methods, member variables, values), method parameters and local variables (such as loop variables and catch parameters). Target is used in the declaration of Annotation type to clarify the target it modifies.

Value(ElementType)yes:

1.CONSTRUCTOR: used to describe the constructor
2.FIELD: used to describe the field
    3.LOCAL_VARIABLE: used to describe local variables
4.METHOD: used to describe the method
5.PACKAGE: used to describe the package
6.PARAMETER: used to describe parameters
7.TYPE: used to describe class, interface (including annotation type) or enum declaration

@Retention defines how long the Annotation is retained: some annotations only appear in the source code and are discarded by the compiler; Others are compiled in class files; Annotations compiled in the class file may be ignored by the virtual machine, while others will be read when the class is loaded (please note that it does not affect the execution of the class, because Annotation and class are separated in use). Use this meta Annotation to limit the "life cycle" of an Annotation.

The values (RetentionPoicy) are:

1.SOURCE: valid in source file (i.e. source file retention)
2.CLASS: valid in class file (i.e. class reserved)
3.RUNTIME: valid at runtime (i.e. reserved at runtime)

@Documented:

This attribute is used to describe that other types of annotation should be used as the public API of the annotated program members, so it can be documented by tools such as javadoc. Documented is a tag annotation with no members.

@Inherited:

@Inherited meta annotation is a tag annotation, @ inherited describes that a marked type is inherited. If an annotation type decorated with @ inherited is used for a class, the annotation will be used for the subclass of the class.

Note: @ Inherited annotation type is inherited by the subclass of the marked class. Class does not inherit annotation from the interface it implements, and methods do not inherit annotation from the methods it overloads.

When the Retention of the annotation marked with @ Inherited annotation type is RetentionPolicy.RUNTIME, the reflection API enhances this inheritance. If we use java.lang.reflect to query an annotation of @ Inherited annotation type, the reflection code check will work: check the class and its parent class until the specified annotation type is found, or reach the top level of the class inheritance structure.

Custom annotation:

When using @ interface to customize annotations, it automatically inherits the java.lang.annotation.Annotation interface, and the compiler automatically completes other details. When defining annotations, you cannot inherit other annotations or interfaces@ Interface is used to declare an annotation, and each method in it actually declares a configuration parameter. The name of the method is the name of the parameter, and the return value type is the type of the parameter (the return value type can only be basic type, Class, String and enum). You can declare the default value of the parameter through default.

Define annotation format:
public @interface annotation name {definition body}

Supported data types of annotation parameters:

1. All basic data types (int,float,boolean,byte,double,char,long,short)
2.String type
3.Class type
4.enum type
5.Annotation type
6. Arrays of all types above

How to set parameters in Annotation type:
First, it can only be modified with public or default access rights. For example, String value(); here, set the method as the default type of defaultaul
Second, parameter members can only use eight basic data types: byte, short, char, int, long, float, double and Boolean, and data types such as String, enum, class and annotations, as well as arrays of these types. For example, String value(); the parameter member here is String
Third, if there is only one parameter member, it is best to set the parameter name to "value" followed by parentheses. Example: the FruitName annotation in the following example has only one parameter member.

Keywords: Java Back-end

Added by entropicsinkhole on Tue, 07 Dec 2021 01:26:59 +0200