Java Custom annotation Classes

Source: Internet
Author: User

First, preface

Today when I read the sail code, I saw something new that I hadn't seen before, such as the Java custom annotation class, How to get annotations, how to reflect inner classes, what does this$0 mean? So, learn and tidy up a bit.

Second, code example
ImportJava.lang.annotation.ElementType;Importjava.lang.annotation.Retention;ImportJava.lang.annotation.RetentionPolicy;ImportJava.lang.annotation.Target;ImportJava.lang.reflect.Field;
//Custom annotation class @Target (Elementtype.field) @Retention (retentionpolicy.runtime) @ interface Myannotation {String name () default "Hjzgg";} Public classMain { PublicMain (Class cls) {field[] fields=Cls.getdeclaredfields (); Testannotation obj=NULL; Try{ obj = (testannotation) cls.getconstructors () [0].newinstance ( this); //Get Inner class object } Catch(Exception e) {e.printstacktrace (); } for(Field field:fields) {System.out.println (Field.getname ()+ " " +Field.gettype (). GetName ()); if(!field.getname (). Equals ("this$0") { myannotation annotation = field.getannotation (Myannotation.class); //Get Note class String name=Annotation.name (); Field.setaccessible (true); Try { Switch(name) { Case"Hjzgg": Switch(Field.gettype (). GetName ()) { Case"Int": Case"Java.lang.Integer": Field.set (obj,555); Break; Case"Java.lang.String": Field.set (obj,"Hehe"); Break; } Break; Case"LXKDD": Switch(Field.gettype (). GetName ()) { Case"Int": Case"Java.lang.Integer": Field.set (obj,555); Break; Case"Java.lang.String": Field.set (obj,"Hehe"); Break; } Break; default: Break; } } Catch(Exception e) {e.printstacktrace (); }}} System.out.println (obj); } Public Static voidMain (string[] args)throwsinstantiationexception, illegalaccessexception {NewMain (testannotation.class); } classtestannotation{ Publictestannotation () {} @MyAnnotation (name= "LXKDD") Private intx; @MyAnnotationPrivateString y; Public intGetX () {returnx; } Public voidSetX (intx) { This. x =x; } PublicString GetY () {returny; } Public voidsety (String y) { This. y =y; } @Override PublicString toString () {return"x:" + x + ", Y:" +y; } }}
Iii. Code Analysis 1. How to write custom annotations
 public @Interface  myannotation {       default "hahaha";   }  

Sense is equivalent to

 Public class extends java.lang.annotation.annotation{        private String value = "hahaha";          Public void SetValue (String value) {             this. Value = value;        }           Public String GetValue () {             return  value;         }   

  Custom annotation Class Rules

@interface actually inherits Java.lang.annotation.Annotation, so you cannot inherit other annotation or interface when defining annotation. Java.lang.annotation.Retention tells the compiler how to treat annotation, and when you use retention, you need to provide a Java.lang.annotation.RetentionPolicy enumeration value.

 Public enum retentionpolicy {       //    compiler is not stored in class     after processing annotation The compiler stores the annotation in class, which is the default value       // The compiler stores the annotation in class and can be read by the virtual machine, reflecting the need   }   

Java.lang.annotation.Target tells the compiler annotation where to use the enumeration values that you want to specify Java.lang.annotation.ElementType.

 Public enumElementType {TYPE,//specify the applicable point as class, interface, enumFIELD,//specify the applicable point as fieldMETHOD,//specify the applicable point as methodPARAMETER,//parameter specifying the applicable point as methodCONSTRUCTOR,//specify the applicable point as constructorLocal_variable,//specify to use points as local variablesAnnotation_type,//specify the applicable point for the annotation typePackage//specify the applicable point for the package}

The java.lang.annotation.Documented is used to specify whether the annotation can be written to Javadoc.
Java.lang.annotation.Inherited is used to specify whether the annotation can be inherited by the quilt class when used for the parent class.

Example

ImportJava.lang.annotation.ElementType; Importjava.lang.annotation.Retention; ImportJava.lang.annotation.RetentionPolicy; ImportJava.lang.annotation.Target; @Documented//This annotation can be written to Javadoc@Inherited//this annotation can be inherited .@Target ({Elementtype.constructor,elementtype.method})//indicates that this annotation can only be used for annotation constructors and methods@Retention (Retentionpolicy.class)//indicates that the annotation is stored in class but the VM does not read Public@Interfacemyannotation {String value ()default"Hahaha"; }  
2. How to get custom annotations

The Java.lang.reflect.AnnotatedElement interface provides four methods to access the annotation

 Public Annotation getannotation (Class annotationtype);     Public annotation[] Getannotations ();     Public annotation[] Getdeclaredannotations ();     Public boolean isannotationpresent (Class annotationtype);  

From: http://blog.csdn.net/foamflower/article/details/5946451

Class, Constructor, Field, Method, package, etc. all implement this interface, you can access annotation information through these methods, if you want to access the annotation specified retention for runtime.
Java built-in annotation has an override Deprecated suppresswarnings.
Override is used only for methods, which indicate that the method of the annotation overrides the method of the parent class, and if not, the compiler errors.
Deprecated indicates that the method is not recommended for use.
Suppresswarnings tells the compiler: I know that my code is fine.

What do you mean, 3.this$0?
 Public class Outer {//publicclass Firstinner {//Publicclass Secondinner {//public  class  thirdinner {    }  
}       

Say a scene: when we get an inner class object inner, but want to get its corresponding external class outer, then it can be obtained by this$0. This$0 is a reference to an external class that is automatically reserved by the inner class.

         getinner ();      // Gets a field this$0 information     for an inner class inner //     Filed Outerfield = Inner.getclass (). Getdeclaredfield ("this$0");      //     outerfield.setaccessible (true);      //    
4.java how to reflect inner classes
Class<?> cls = Class.forName ("package. Outerclass$innerclass "class<?> cls = OuterClass.InnerClass.class;
(1)  = (outerclass.innerclass) cls.getconstructors () [0].newinstance (new Outerclass ()
= (Outerclass.innerclass) cls.getconstructor (outerclass. Class). Newinstance (new Outerclass ());

It can be seen that the inner class of the parameterless constructor is obtained through the reflection mechanism, to specify its parent class parameters to be obtained, otherwise the following exception will be reported:

Java.lang.nosuchmethodexception:com.hjzgg.outerclass$innerclass.<init>()    at Java.lang.Class.getConstructor0 (Class.java:3082) at    java.lang.Class.getConstructor (Class.java: 1825)

Java Custom annotation classes

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.