Using the reflection mechanism of Java to get the metadata on annotation __java

Source: Internet
Author: User

First, let's say @retention this annotation

This annotation shows the time at which annotations exist on the class

@Retention can set three values

1 The Retentionpolicy.runtime compiler will record the annotation in the class file, and the VM will retain the annotation at runtime, so it can be read in a reflective way.

2 The Retentionpolicy.class compiler will record the annotations in the class file, but the VM does not need to keep annotations at run time.

3) retentionpolicy.source The compiler to discard the annotations.

Retentionpolicy is an enumeration that has three values, respectively, Source,class,runtime

However, only @retention (Retentionpolicy.runtime) can be added to a custom annotation to allow the reflection mechanism to be dynamically obtained when the program is running.


@Retention (retentionpolicy.runtime)
@Target ({elementtype.annotation_type,elementtype.method, Elementtype.type,elementtype.package,elementtype.parameter})
@Documented public
@interface result 
{
	String value ();
	
	String[] Arrays (); 
}


The annotation metadata can be obtained by using the following Java reflection code.

/**
* Reflection Acquisition Annotation
*
* Class<?> clazz = class.forname ("Org.oa.test.JdbcTest");
*
* Method SayHello = Clazz.getmethod ("SayHello");
*
* annotation[] annotations = clazz.getdeclaredannotations ();
*
* Result result = (result) annotations[0];
*
* SYSTEM.OUT.PRINTLN (Result.arrays () [1]);
*
*
*/



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.