Java Extracurricular Development-----reflection and annotations

Source: Internet
Author: User

One: Reflection (Reflect) 1.1, overview

Summary: the ability to dynamically get the information of a class and the way the object is called dynamically (the way the runtime obtains and uses the class's information is called Reflection )

1.2. Main functions

  Main functions:

      •  Determine the class to which any object belongs at run time;
      • Constructs an object of any class at run time;
      • Determine the member variables and methods of any class at run time;
      • Methods to invoke any object at run time
1.3. Class

Explanation of class:

      • class defines the keywords for the classes
      • Class static properties for each class
      • Class class describes type information for classes

1.4, reflection commonly used methods
How to get Class
Get through objects Object. GetClass ()
obtained by string (package name + class name) Class.forName ("package name. Class Name")
Get class by static members of class Class name.
Only for built-in base data types (string is reference data type ) The reference type of the base data type. TYPE such as: Integer.type

Other methods
Get all of your own fields Field[] Field=class.getdeclaredfields ();
Get all the public fields (including the parent class) Field[] Field=class.getfields ();
Get method (based on method name) Class.getmethod ("Method name");
Calling methods Method.invoke (object, parameter plus parameter);
Get Instance Object Class.newinstance
Set private fields to access Class.setaccessible (TRUE);
Two: Reflection Scenario Three: Annotations 3.1, definition of annotations

Java annotations, like modifiers, can be used to extract documents from Java code, track dependencies in code, or check at compile time. Annotations can be applied to the declarations of packages, classes, methods, member variables, parameters, and local variables. The first note that most of us touch is @override.

Annotations work by using annotations to decorate the Java code, and then another piece of code called the annotation processor parses the note and the modified code and handles it accordingly.

3.2. Built-in annotations

1.) Override

Java.lang.Override is a marker type annotation, which is used as a labeling method. It illustrates the way that the annotated method overloads the parent class and plays the role of the assertion. If we use this annotation in a method that does not overwrite the parent class method, the Java compiler warns with a compilation error.

2.) Deprecated

Deprecated is also a marker type annotation. When a type or type member uses the @deprecated modifier, the compiler will not encourage the use of this annotated program element. So using this modification has a certain "continuity": if we use this obsolete type or member in the code by inheriting or overwriting it, although the inherited or overwritten type or member is not declared as @deprecated, the compiler still has to call the police.

3.) suppresswarnings

Suppresswarning is not a marker type annotation. It has a member of type string[], and the value of this member is the forbidden warning name. For the Javac compiler, the warning name that is valid by the-xlint option is also valid for @suppresswarings, and the compiler ignores the unrecognized warning name.
@SuppressWarnings ("Unchecked")

3.3, meta-annotations (annotated annotations)

Java.lang.annotation provides four types of meta-annotations that specifically annotate other annotations (you need to use the meta-annotations when customizing annotations):

@Documented – whether the annotations will be included in the Javadoc

@Retention – When to use this annotation

@Target – where the annotations are used

@Inherited – whether subclasses are allowed to inherit the annotation

Four: Custom annotations

Some rules written by custom annotation classes:
1. The annotation type is defined as @interface, and all annotation automatically inherit the Java.lang.Annotation interface and can no longer inherit other classes or interfaces.

2. Parameter members can only be decorated with public or default

3. Parameter members can only use basic types Byte,short,char,int,long,float,double,boolean eight basic data types and string, Enum, Class, annotations and other data types. As well as these types of arrays.

4. To get the annotation information for a class method and a field, you must get the annotation object through the Java reflection technique, because you have no other way to get the annotation object

5. Annotations can also have no members defined, custom annotations need to use to meta annotations

Case:

 PackageAnnotation;Importjava.lang.annotation.*; @Retention (retentionpolicy.runtime) @Target (value={elementtype.field,elementtype.type}) @Inherited Public@InterfaceAilas { PublicString value ()default"";  Public  BooleanIsgenerator ()default false;  Public  BooleanIsNull ()default true;  Public  BooleanIsprimary ()default false;}
V: Reflection combined with annotations

Generate a simple SQL script

 PackageAnnotation;ImportJava.lang.reflect.Field; Public classCreatesqlscript { Public Static voidMain (string[] mag)throwsException {System.out.println ("Query:" +creteselectscript ("Fruits")); System.out.println ("Modified:" +creteupdatescript ("Fruits")); System.out.println ("Delete:" +cretedeletescript ("Fruits")); System.out.println ("Add:" +creteinsertscript ("Fruits")); System.out.println ("NEW:" +cretetablescript ("Fruits"))); }     Public StaticString Creteselectscript (String clas)throwsException {String sqlselect= "Select"; Class Clazz= Class.forName ("reflect." + Clas + ""); Field[] Fields=Clazz.getdeclaredfields (); String Temp= "";  for(Field f:fields) {sqlselect+ = temp +F.getname (); Temp= ","; } sqlselect+ = "form"; Ailas Classalias= (Ailas) clazz.getdeclaredannotation (Ailas.class); if(Classalias! =NULL) {            //to get the value of values in annotationsSqlselect + = "" +Classalias.value (); } Else{sqlselect+= " " +Clazz.getsimplename (); }        returnSqlselect; }     Public StaticString Creteupdatescript (String clas)throwsException {Class clazz= Class.forName ("reflect." + Clas + ""); String SQL= "Update";//UPDATE student SET sname= "Li June" WHERE sno= "101"Ailas Classalias = (Ailas) clazz.getdeclaredannotation (Ailas.class); if(Classalias! =NULL) {            //to get the value of values in annotationsSQL + = "" + classalias.value () + ""; } Else{SQL+ = "" + clazz.getsimplename () + ""; } field[] fields=Clazz.getdeclaredfields (); SQL+ = "Set"; String Temp= ""; String Primary="";  for(Field f:fields) {Ailas Fieldalias= F.getdeclaredannotation (Ailas.class); if(fieldalias!=NULL){                if(Fieldalias.isprimary ()) {primary=F.getname (); Continue; }} SQL+ = temp + f.getname () + "=?"; Temp= ","; } SQL+ = "where" + primary + "=?"; returnSQL; }     Public StaticString Cretedeletescript (String clas)throwsException {Class clazz= Class.forName ("reflect." + Clas + ""); String SQL= "DELETE from";//DELETE from Fruits WHERE name= "Watermelon"Ailas Classalias = (Ailas) clazz.getdeclaredannotation (Ailas.class); if(Classalias! =NULL) {            //to get the value of values in annotationsSQL + = "" + classalias.value () + ""; } Else{SQL+ = "" + clazz.getsimplename () + ""; } field[] fields=Clazz.getdeclaredfields (); SQL+ = "form"; SQL+ = "where" + fields[0].getname () + "=?"; returnSQL; }     Public StaticString Creteinsertscript (String clas)throwsException {Class clazz= Class.forName ("reflect." + Clas + ""); String SQL= "INSERT INTO";//INSERT INTO Student (Sno,sname,ssex,sbirthday,class) VALUES (' 108 ', ' Zeng Hua ', ' Male ', ' 1977-09-01 ', ' 95033 ');Ailas Classalias = (Ailas) clazz.getdeclaredannotation (Ailas.class); if(Classalias! =NULL) {            //to get the value of values in annotationsSQL + = "" + classalias.value () + "("; } Else{SQL+ = "" + clazz.getsimplename () + "("; } field[] fields=Clazz.getdeclaredfields (); String Temp= "";  for(Field f:fields) {SQL+ = temp + f.getname () + ""; Temp= ","; } SQL+ = ") VALUES ("; Temp= "";  for(Field f:fields) {SQL+ = temp + "?"; Temp= ","; } SQL+= ")"; returnSQL; }     Public StaticString Cretetablescript (String clas)throwsException {Class clazz= Class.forName ("reflect." + Clas + ""); String SQL= "CREATE TABLE";/// * CREATE TABLE Student/* Student Watch * ///        (////Sno Char (3) NOT NULL PRIMARY key,/* study number (Master code) */////Sname Char (8) NOT NULL,/* Student name * /////Ssex Char (2) NOT NULL,/* Student sex */////sbirthday datetime,/* Student Birth date * ///Class Char (5)/* Student's class *///)*/Ailas Classalias = (Ailas) clazz.getdeclaredannotation (Ailas.class); if(Classalias! =NULL) {            //to get the value of values in annotationsSQL + = "" + classalias.value () + "("; } Else{SQL+ = "" + clazz.getsimplename () + "("; } field[] fields=Clazz.getdeclaredfields (); String Temp= "";  for(Field f:fields) {string[] type= F.gettype (). toString (). Split ("[.]"); SQL+ = temp + f.getname () + ""; if(type[(Type.length)-1].equals ("String") ) {SQL+ = "varchar"; } Else if(type[(Type.length)-1].equals ("Double") ) {SQL+ = "Money"; } Else if(type[(Type.length)-1].equals ("Date") ) {SQL+ = "datetime"; } Ailas Fieldalias= (Ailas) f.getdeclaredannotation (Ailas.class); if(Fieldalias! =NULL) {                if(!Fieldalias.isnull ()) {SQL+ = "NOT NULL"; }                if(Fieldalias.isprimary ()) {SQL+ = "PRIMARY Key"; }} Temp= ","; } SQL+= ")"; returnSQL; }}

Java Extracurricular Development-----reflection and annotations

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.