Reflection and annotations in Java

Source: Internet
Author: User

Reflection

Reflection is the abstraction of classes into a class object. Consider a class as an object, analyze its construction methods, member variables, methods, and inner classes.
The analysis of the class is to abstract the class into class object, and the analysis of the construction method is to abstract the construction method into the object of the constructor class, and the analysis of the member variable is to abstract the variable into the object of the Feild class, and the analysis of the method is the object of the method class.
As an example:

1  Public classStudent {2      PublicString name;//Define student names3     Private intAge//Define student Age4     PrivateString sex;//Define student gender5     //How to get the student's name6      PublicString GetName () {7         returnname;8     }9     //methods of assigning students ' namesTen      Public voidsetName (String name) { One          This. Name =name; A     } -     //How to get a student's age -      Public intGetage () { the         returnAge ; -     } -     //Note that there is no way to assign a student's age to a private type.  -  +     //ways to get a student's gender -      PublicString Getsex () { +         returnsex; A     } at     //the method of students ' gender assignment -      Public voidsetsex (String sex) { -          This. Sex =sex; -     } -}
1  Public classTest {2      Public Static voidMain (string[] args) {3Class<student> Clazz =student.class;4         Try {5/the use of Class Field method. 6 7             //Gets the Name Property object for the student class. 8Field field1 = Clazz.getdeclaredfield ("name");9             //returns the modifier for the name fieldTen System.out.println (Field1.getmodifiers ()); One             //returns the type of the name field A System.out.println (Field1.gettype ()); -             //returns the name of the names field - System.out.println (Field1.getname ()); the             //gets all the property objects of the student class.  -field[] Field2 =clazz.getdeclaredfields (); -             //Traverse All Properties -              for(Field field:field2) { + System.out.println (Field.getname ()); - System.out.println (Field.gettype ()); + System.out.println (Field.getmodifiers ());  A             } at  -             //Zhangsan for Student objects private type with no Set method age assignment -Student Zhangsan =NewStudent (); -             //object that gets the Age property -Field age = Clazz.getdeclaredfield ("Age"); -             //cancels the check access to the modifier of the Age property to assign a value to the Age property inAge.setaccessible (true); -             //Assigning a value to the Age property toAge.set (Zhangsan, 18); +             //reply to check access to the modifiers of the Age property -Age.setaccessible (false); the System.out.println (Zhangsan.getage ()); *  $             //Use of MethodPanax NotoginsengMethod method1= Clazz.getdeclaredmethod ("GetName"); -System.out.println (Method1.getmodifiers ());
Annotations (Annotation)

Definition of annotations:

1  @Interface  Note name {2      Default ' < defaults > ';3     ... 4  }

The following example defines an annotation named Myanotation, which contains a member of type int's value (). @Retention represents the scope of application of annotations, the scope of application of annotations is usually represented by enumeration constants in Retentionpolicy, the runtime constants in Retentionpolicy in this example, which indicate the maximum effective range for loading annotations to virtual machines at run time. @Target indicates that the secondary annotation applies to the variable type and can assign a value to a variable of type int.

This image is excerpted from the blog park ... @ black humor lion

1 @Retention (retentionpolicy.runtime) 2 @Target (Elementtype.field) 3  public @Interface  myanotation {4     int  value (); 5 }
1 ImportJava.lang.reflect.Field;2 3  Public classStudent {4     PrivateString name;5@MyAnotation (Value =18)6     Private intAge ;7 Student () {8Class clazz = Student.class;9         Try {Ten             //get the Age Property object OneField field = Clazz.getdeclaredfield ("Age"); A             //Create annotation objects to get annotations for the Age property -Myanotation ma = field.getannotation (myanotation.class); -             //determines whether the obtained annotation object is empty the             if(ma!=NULL){ -                 //assign a value to age -                 inti =Ma.value (); -Field.setaccessible (true); +Field.set ( This, i); -Field.setaccessible (false);  +             }            A}Catch(Nosuchfieldexception |SecurityException e) { at             //TODO auto-generated Catch block - e.printstacktrace (); -}Catch(IllegalArgumentException e) { -             //TODO auto-generated Catch block - e.printstacktrace (); -}Catch(illegalaccessexception e) { in             //TODO auto-generated Catch block - e.printstacktrace (); to         }        +     }    -      PublicString GetName () { the         returnname; *     } $      Public voidsetName (String name) {Panax Notoginseng          This. Name =name; -     } the      Public intGetage () { +         returnAge ; A     } the      Public voidSetage (intAge ) { +          This. Age =Age ; -     }    $}

Reflection and annotations in Java

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.