Java reflection mechanism and annotation

Source: Internet
Author: User

Transferred from: http://justjavac.iteye.com/blog/714654

Java reflection is a very important feature of the Java language. It allows a running Java program to check itself and to manipulate the internal properties of the program directly. For example, you can use it to get the names of the members in the Java class and display them.

The Java reflection mechanism mainly provides the following features:

A Determine the class to which any object belongs at run time.

B. Constructs an object of any class at run time.

C At run time, determine the member variables and methods that any one class has.

D. A method that invokes any object at run time.

In the JDK, the Java reflection mechanism is implemented primarily by the following classes, which are in the Java.lang.reflect package:

Class: Represents a Class.

Field class: Represents a member variable of a class (a member variable is also called a property of a class).

Method class: Methods that represent classes.

Constructor class: Represents the construction method of a class.

Array class: Provides a static method for dynamically creating an array, and for accessing the elements of an array.

Here is a program: a POJO class was designed. The so-called POJO class, I superficial understanding namely and JavaBean similar, only the field and Setter/getter method. Then in the main function through reflection, the console prints all the fields and methods of the POJO class.
I designed the POJO class to be Workerpojo.java, and then another test class is Pojoreflection.java, which is responsible for printing all the fields and methods of the class in the main function. See the procedure below:

Workerpojo.java:

 Packagecom.xpec.landon.trainjava.annotation;/*** Pojo class, similar to JavaBean *@authorLvwenyong **/ Public classworkerpojo{PrivateString name; Private intAge ; /*** Modified with annotation *@returnname*/@WorkerPOJOAnnotation (Name= "Landon", age = 22)   PublicString GetName () {returnname;}  Public voidsetName (String name) { This. Name =name;}  Public intGetage () {returnAge ;}  Public voidSetage (intAge ) { This. Age =Age ;}}


Pojoreflection.java:

 Packagecom.xpec.landon.trainjava.annotation;ImportJava.lang.reflect.Field;ImportJava.lang.reflect.Modifier;ImportJava.lang.reflect.Method;/*** Use the Java reflection mechanism to output the fields and methods of the Pojo class (New annotation decoration) *@authorLvwenyong **/ Public classPojoreflectiontest { Public Static voidMain (string[] args) {Try   {   //load Workpojo, note that you must write the full class name, including the package name, because the package name is part of the class nameClass Pojo = Class.forName ("Com.xpec.landon.trainjava.annotation.WorkerPOJO"); //get an array of fieldsField []fieldlist =Pojo.getdeclaredfields (); //gets an array of methodsMethod []methodlist =Pojo.getdeclaredmethods (); System.out.println ("All fields of the Workerpojo class:"); System.out.println ("Modifier" + "+" type "+" + "field name");  for(inti = 0;i < fieldlist.length;i++) {Field field=Fieldlist[i]; //get the specific modifier in the following formSystem.out.println (Modifier.tostring (Field.getmodifiers ()) + "" + field.gettype () + "" +field.getname ());   } System.out.println (); System.out.println ("All methods of the Workerpojo class (not including annotation-modified methods):");  for(intj = 0;j < methodlist.length;j++) {Method method=Methodlist[j]; //Judging whether the method is annotation modified    BooleanMethodannotation = Method.isannotationpresent (workerpojoannotation.class); //if modified by annotation, the method is filtered out, i.e. no output    if(methodannotation) {Continue; }    //Get method parameter listClass parameters[] =method.getparametertypes (); System.out.print (Modifier.tostring (Method.getmodifiers ())+ "" + method.getreturntype () + "" + method.getname () + "(");  for(intK = 0;k < parameters.length;k++) {System.out.print (parameters[k].tostring ()); } System.out.println (")"); }  }  Catch(ClassNotFoundException exception1) {exception1.printstacktrace (); }   }}

Here is a run of the program:



As you can see, the annotation is introduced in the Workerpojo class.

Below, we introduce annotation in detail:
In using JUNIT4, we can see that there is a @Test tag in front of each test method, which is the legendary Annotation.
Annotation provides a way to associate any information or any meta-data (metadata) with the program element. In some ways, annotation is used like a modifier and is applied to the declaration of a package, a type, a constructor method, a method, a member variable, a parameter, a local variable. This information is stored in the annotation "name=value" structure pair. The annotation type is an interface that provides access to its information through the Java reflection API.
Annotation can be used to associate any information with a program element (class, method, member variable, and so on). It is important to note that there is a basic unspoken rule: annotaion does not affect the execution of program code, regardless of the addition or deletion of annotation, the code is consistently executed. In addition, while some annotation are accessed at run time through the Java Reflection API approach, the Java language interpreter ignores these annotation when it works. It is the Java virtual machine that ignores the annotation, which causes the annotation type to "not work" in the code, and the information in the annotation type is accessed and processed only by a matching tool.
Annotation is a callout that relates information or metadata to a program element. It never affects
The execution of the AVA program, but has implications for such as compiler warnings or accessibility tools like document generators.
My understanding is: Annotation is inherited fromjava.lang.annotation.AnnotationClass that provides information about the Package class field methed to the Program analysis tool or virtual machine, and it is no different than the other classes except the way it is used.
A simple Annotation:WorkerPOJOAnnotation.java is written below.

 Packagecom.xpec.landon.trainjava.annotation;Importjava.lang.annotation.Documented;ImportJava.lang.annotation.ElementType;Importjava.lang.annotation.Retention;ImportJava.lang.annotation.RetentionPolicy;ImportJava.lang.annotation.Target;/*** A annotation that modifies the Workerpojo class method *@authorLvwenyong **/@Target (Elementtype.method) @Retention (retentionpolicy.runtime) @Documented Public@Interfaceworkerpojoannotation {String name ();intAge ();}


The ElementType inside the @Target is used to specify which elements the Annotation type can be used on, including type, method, field (fields), PARAMETER (parameter), and so on. Where type refers to types that can be used on class,interface and so on. The following gives the static variables in the ElementType that are deserialized with Jad:

In addition, the retentionpolicy in the @Retention refers to the information retention methods in Annotation, respectively, Source,class and RUNTIME. Source represents the Annotation type of information will only be retained in the program source code, if the source code is compiled, the Annotation data will disappear, and will not be kept in the compiled. class file. ClASS means that this annotation type of information is kept in the program source code, but also in the compiled. class file, and does not load this information into the virtual machine (JVM) when it is executed. Note that when you do not set a Retention value for a Annotation type, the system default value is class. The third, RUNTIME, indicates that the information is preserved in the source code, the compiled. class file, and this information is loaded into the JVM when it is executed.
The following is a list of the static variables in the Retentionpolicy compiled with Jad

The last one[email protected]The purpose is to let this Annotation type of information be displayed on the Java API documentation.

The workerpojoannotation of the above design is applied in front of a method of the Workerpojo class:


Then the console outputs fields and methods that are not Annotation annotated, and you can see that the GetName method is not included when you run it.
Finally we can write a test case with JUNIT4: Pojoreflectionjunit4test. java

 Packagecom.xpec.landon.trainjava.annotation;ImportJava.lang.reflect.Field;ImportJava.lang.reflect.Method;ImportJavax.activation.FileDataSource;ImportJunit.framework.Assert;ImportOrg.junit.After;ImportOrg.junit.Before;Importorg.junit.Test;/*** A testcase about Java reflection and annotation *@authorLvwenyong **/ Public classPojoreflectionjunit4test {PrivateClass Pojo;PrivateField []fieldlist;Privatemethod[] methodlist; @Before Public voidSetUp ()throwsException {//Load Class WorkpojoPojo = Class.forName ("Com.xpec.landon.trainjava.annotation.WorkerPOJO"); //get an array of fieldsFieldList =Pojo.getdeclaredfields (); //gets an array of methodsMethodList =pojo.getdeclaredmethods ();} //test the number of fields and methods@Test Public voidtestsize () {assert.assertequals (2, fieldlist.length); Assert.assertequals (4, methodlist.length); } //test field with annotations@Test Public voidisfieldannotation () { for(inti = 0;i < fieldlist.length;i++) {assert.assertequals (false, Fieldlist[i].isannotationpresent (workerpojoannotation.class)); } }  //test method with annotations@Test Public voidismethodannotation () { for(inti = 0;i < methodlist.length;i++) {assert.assertequals (false, Methodlist[i].isannotationpresent (workerpojoannotation.class)); }} @After Public voidTearDown ()throwsException {}}

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.