Customize annotations in Java and get annotation property values through reflection

Source: Internet
Author: User

Directly on the code, note in the note:

1, define the custom annotation class (class annotation and field annotation):

Package Com.uno.ray;
Import java.lang.annotation.Documented;
Import Java.lang.annotation.ElementType;
Import java.lang.annotation.Inherited;
Import java.lang.annotation.Retention;
Import Java.lang.annotation.RetentionPolicy;
Import Java.lang.annotation.Target;

Import Java.net.Authenticator.RequestorType; /** * Custom Annotation * @author Uno * @Documented: Indicates that the annotation can be used to generate a doc * @Inherited: The annotation can be automatically inherited * @Retention: Indicate at what level the annotation is displayed: * Retentionpo Licy. The source annotation exists in the sources and is discarded at compile time retentionpolicy.class annotations are compiled into the CLASS file, but the JVM ignores the retentionpolicy.runtime JVM reads annotations, It is also saved to the class file @Target: Indicates that the annotation can be annotated with the program scope Elementtype.type for classes, interfaces, enumerations, but not annotations Elementtype.field in fields, including enumeration values Elementtype.me Thod acts on the method, does not include the construction method elementtype.parameter the parameters acting on the method elementtype.constructor the construction method elementtype.local_veriable Action on the local variable or catch statement Elementtype.annotation_type action on the annotation Elementtype.package action on the packet/@Documented @Inherited @Retention (reten Tionpolicy.runtime) @Target ({elementtype.type, Elementtype.field})//The secondary annotation acts on the public @interface field on the Class and fieldtypeannotation {/** *leip December 3, 2016 *todo **/String type () default "Ignore";
	int age () default 27; String[] Hobby ();
 Defalut is not specified, it needs to be explicitly indicated at the time of the annotation
2. (Method Annotation)

Package Com.uno.ray;

Import java.lang.annotation.Documented;
Import Java.lang.annotation.ElementType;
Import java.lang.annotation.Inherited;
Import java.lang.annotation.Retention;
Import Java.lang.annotation.RetentionPolicy;
Import Java.lang.annotation.Target;

/** * * * 
 @author Uno * *
/@Documented @Inherited
@Retention ( Retentionpolicy.runtime)
@Target (Elementtype.method)//secondary annotations can only be used on method public
@interface Methodannotation {

	String desc () default "Method1";
}

3, the Definition Test class: (Reflection Class)

Package Com.uno.ray;
Import Java.awt.Dialog.ModalityType;
Import Java.lang.reflect.Field;
Import Java.lang.reflect.Method;

Import Java.util.Arrays;
	 @FieldTypeAnnotation (type = "Class", hobby = {"Smoke"}) public class Reflectannotation {/** * LEIP December 3, 2016 TODO

	**/@FieldTypeAnnotation (hobby = {"Sleep", "Play"}) private String Maomao;
	
	@FieldTypeAnnotation (hobby = {"Phone", "buy"}, age = +, type = "normal") private String zhangwenping; @MethodAnnotation () public void Method1 () {} @MethodAnnotation (desc= "method2") public void Method2 () {} pub Lic static void Main (string[] args) {//here to parse the annotations in the field with reflection class<reflectannotation> CLZ = Reflectannotation.clas
		S
		Determine if there is a secondary annotation on the class Boolean clzhasanno = Clz.isannotationpresent (Fieldtypeannotation.class);
			if (Clzhasanno) {//Get the annotation on the class fieldtypeannotation annotation = Clz.getannotation (Fieldtypeannotation.class);
			attributes on output annotations int age = Annotation.age (); string[] Hobby = annotation.hobby ();
			String type = Annotation.type ();
		System.out.println (Clz.getname () + "age =" + age + ", hobby =" + arrays.aslist (Hobby). ToString () + "type =" + type); //Resolve whether there is a note//Ps:getdeclaredfields on the field that returns all the declared fields of the class, including private, protected, public, but not the parent//GetFields: All PU containing the parent class is returned
		Blic fields, as GetMethods () field[] fields = Clz.getdeclaredfields ();
			for (Field Field:fields) {Boolean Fieldhasanno = Field.isannotationpresent (Fieldtypeannotation.class);
				if (Fieldhasanno) {fieldtypeannotation Fieldanno = field.getannotation (Fieldtypeannotation.class);
				Output annotation Property int age = Fieldanno.age ();
				string[] Hobby = fieldanno.hobby ();
				String type = Fieldanno.type (); System.out.println (Field.getname () + "age =" + age + ", hobby =" + arrays.aslist (Hobby). ToString () + "type =" + type)
			;
		}//parsing method annotation method[] methods = Clz.getdeclaredmethods ();
			For (method Method:methods) {Boolean Methodhasanno = Method.isannotationpresent (Methodannotation.class); If(Methodhasanno)
				{//get annotation methodannotation Methodanno = method.getannotation (Methodannotation.class);
				Output annotation attribute String desc = Methodanno.desc ();
			System.out.println (Method.getname () + "desc =" + desc);
 }
		}
	}
}

4, output

Com.uno.ray.ReflectAnnotation age = +, hobby = [Smoke] type = Class
Maomao age = +, hobby = [sleep, play] type = IGN Ore
zhangwenping age =-Hobby = [phone, buy] type = Normal
method2 desc = method2 method1 desc
= method1


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.