Java Custom Annotations

Source: Internet
Author: User

I. Custom annotation Classes

Target limits the scope of use of annotations

TYPE,
For classes, interfaces, enumerations, but not annotations
FIELD,
field, including the enumeration value
METHOD,
methods, not including construction methods
PARAMETER,
Parameters of the method
CONSTRUCTOR,
Construction method
Local_variable,
Local variable or catch statement
Annotation_type,
Annotation type (no data) Package//java package

Retention Processing Strategy

  SOURCE,  //此类型会被编译器丢弃  CLASS,  //此类型注解会保留在class文件中,但JVM会忽略它  RUNTIME  //此类型注解会保留在class文件中,JVM会读取它
@Target (Elementtype.field) @Retention (retentionpolicy.runtime)  public @Interface  Name {    default "Apple";    }

Two. Using annotations

 Public class annottiontest {        @Name ("banana")    private  String Name;      Public String GetName () {        return  name;    }      Public void setName (String name) {        this. Name = name;    }     } 

Three. Annotation Processing class

 Public classUtil { Public Static voidGetInfo (class<?>clazz) {String StrName= "Name:"; Field[] Fields=Clazz.getdeclaredfields ();  for(Field field:fields) {if(Field.isannotationpresent (Name).class) {name Name= (name) field.getannotation (name).class); StrName=strname+Name.value ();                System.out.println (StrName); } }} @Test Public voidFun () {util.getinfo (annottiontest).class); }}

Java Custom 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.