Java custom annotations and values to get annotations

Source: Internet
Author: User

1. Custom annotations

Import java.lang.annotation.*; @Documented @target (Elementtype.field) @Inherited @retention (retentionpolicy.runtime) Public@interface Myanno {/** * can be null * @return*/boolean iscannull ()default true; /** * can be an empty string * @return*/boolean iscanempty ()default true; /** * can be 0 * @return*/boolean Iscanzero ()default true;}

2. Use annotations:

 Public classMouse {@MyAnno (iscannull=true)    PrivateString name; @MyAnno (Iscannull=false, Iscanzero =false)    Private  intAge ; @MyAnno (Iscannull=false)    PrivateString address; @MyAnno (Iscanzero=false)    Private DoubleMoney ;  PublicString getaddress () {returnaddress; }     Public voidsetaddress (String address) { This. Address =address; }     Public DoubleGetmoney () {returnMoney ; }     Public voidSetmoney (DoubleMoney ) {         This. Money =Money ; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }}

3. Get the value of the note and judge it

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 classIntactcheckutil { Public Staticboolean check (Object obj) {//list = Arrays.aslist (AnnotationParsing.class.getClassLoader (). LoadClass (((Class) obj). GetClass (). GetName ()). Getdeclaredfields ());list<field> list =arrays.aslist (Obj.getclass (). Getdeclaredfields ());  for(intI=0; I<list.size (); i++) {Field field= list.Get(i); if(Field.isannotationpresent (Myanno.class)){//whether to use Myanno annotations                 for(Annotation anno:field.getDeclaredAnnotations ()) {//get all the annotations                    if(Anno.annotationtype (). Equals (Myanno.class) ){//Find your own annotations                        if(! ((Myanno) anno). Iscannull ()) {//value of the annotation                            if(Testutil.getfieldvaluebyname (Field.getname (), obj) = =NULL){                                Throw NewRuntimeException ("class:"+mouse.class+"Properties of:"+field.getname () +"cannot be empty, the actual value:"+testutil.getfieldvaluebyname (Field.getname (), obj) +", Note: field.getdeclaredannotations ()"); }                        }                        if(!((Myanno) anno). Iscanempty ()) {                            if(Testutil.getfieldvaluebyname (Field.getname (), obj). Equals ("")){                                Throw NewRuntimeException ("class:"+mouse.class+"Properties of:"+field.getname () +"cannot be an empty string, the actual value:"+testutil.getfieldvaluebyname (Field.getname (), obj) +", Note: 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 NewRuntimeException ("class:"+mouse.class+"Properties of:"+field.getname () +"cannot be a null character 0, the actual value:"+testutil.getfieldvaluebyname (Field.getname (), obj) +", Note: field.getdeclaredannotations ()"); }                        }                    }                }            }        }        return  true; }}

Note: Note the use of each parameter (the following is from the Internet http://www.cnblogs.com/peida/archive/2013/04/24/3036689.html)

@Target:

@Target illustrates the range of objects that annotation modifies: annotation can be used for packages, types (classes, interfaces, enumerations, annotation types), type members (methods, constructor methods, member variables, enumeration values), Method parameters and local variables (such as loop variables, catch parameters). Target can be more clearly decorated by using target in the declaration of the annotation type.

The VALUES (ElementType) are:

1.CONSTRUCTOR: Used to describe the constructor
2.FIELD: Used to describe the domain
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 classes, interfaces (including annotation types) or enum declarations

@Retention defines how long the annotation is retained: Some annotation appear only in the source code and are discarded by the compiler, while others are compiled in the class file The annotation that are compiled in the class file may be ignored by the virtual machine, while others will be read when class is loaded (note that it does not affect class execution because annotation is separated from the class in use). Using this meta-annotation can limit the "life cycle" of annotation.

The values (Retentionpoicy) are:

1.SOURCE: Valid in source file (i.e., source file retention)
2.CLASS: Valid in class file (that is, class reserved)
3.RUNTIME: Valid at run time (that is, runtime retention)

@Documented:

  This property is used to describe other types of annotation that should be used as public APIs for annotated program members, so they can be documented by tools such as Javadoc. Documented is a markup annotation with no members.

@Inherited:

  @Inherited meta-annotation is a markup annotation, @Inherited illustrates that a type that is labeled is inherited. If a annotation type that uses the @inherited modifier is used for a class, the annotation will be used for subclasses of that class.

Note: @Inherited the annotation type is inherited by subclasses of the class being labeled. The annotation class does not inherit from the interface it implements, and the method does not inherit annotation from the method it overloads.

The reflection API enhances this inheritance when the retention of the @inherited annotation type callout annotation is retentionpolicy.runtime. If we use Java.lang.reflect to query the annotation of a @inherited annotation type, the reflection code check will work: Examine the class and its parent class until the specified annotation type is found, or reach the top level of the class inheritance structure.

Custom annotations:

When you use @interface to customize annotations, the Java.lang.annotation.Annotation interface is automatically inherited and other details are automatically completed by the compiler. When you define annotations, you cannot inherit other annotations or interfaces. @interface is used to declare an annotation, in which each method 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 base type, Class, String, enum). You can declare the default value of a parameter through default.

  To define the annotation format:
Public @interface annotation name {definition body}

  Supported data types for 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 the parameters of the annotation type:
First, it can only be decorated with public or default access rights. For example, String value (); Here the method is set to Defaul default type;
Second, parameter members can only use basic types Byte,short,char,int,long,float,double,boolean eight basic data types and string,enum,class,annotations data types, As well as these types of arrays. For example, String value (), where the parameter member is string;
Thirdly, if there is only one parameter member, it is best to set the parameter name to "value", followed by parentheses. Example: The following example Fruitname annotation has only one parameter member.

Simple custom annotations and examples of using annotations:

    

Java custom annotations and values to get annotations

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.