java - reflections, annotations

Reflected note: You must grasp reflex before looking at notes

https://www.cnblogs.com/clamp7724/p/11655237.html

https://www.cnblogs.com/clamp7724/p/11658557.html

annotation:

Notes the role:

1. Use only as comments suggest that there is no practical significance

2. Verify prompt code error, such as @override verifies the following method is not the right to rewrite the parent class method, if there is wrong will be displayed before compilation

3. carry some information as a container to carry information, similar to the variable?

 

Use annotations:

Package AnnotationTest; 


Import java.lang.annotation.Annotation;
 Import as java.lang.reflect.Field;
 Import java.lang.reflect.InvocationTargetException;
 Import the java.lang.reflect.Method; 

public  class annotationClass {
     // annotation using the format:
     @ @ annotation 

    // annotation positions:
     // class constructor method, the above properties 

    // annotation action:
     @ 1 as a comment
     // 2 check
     // such as the following would indicate that a rewrite override the method, if the method is the wrong format, will compile errors (some compilers will be below the red line in the Override), let us know that does not meet specifications rewrite. 
    @Override
     public String toString () {
        return  Super .toString (); 
    } 

    // 3. carry some information 
    @SuppressWarnings ({ "unused", "Serial" }) 
    String S = "AAA" ;
     // SuppressWarning which add String [], can be used to eliminate some warnings not recommended, because warnings are generally expressed compilation problems
     // such as adding unused represented the following variables are not used
     // serial inherited Serializable version does not add serial numbers
     // deprecation outdated methods
     // uncheck Do not check generic issues detecting (occasionally used)
     // All warning not all questions (better not to use) 


    // use their own annotations 
@ annotation structure: See note particularly the class definition comments
// @Target ({ElementType.FIELD, the ElementType .method, ElementType.CONSTRUCTOR}) //Before property can be used, the method, constructor, there are other elements, with the ElementType Get // @Retention (RetentionPolicy.RUNTIME) // run when used, as well as source code, compile time. Pick-RetentionPolicy // @Inherited // comment be inherited // @Documented // can be changed to a document, not commonly // public @interface MyAnnotation {// structurally similar interface (Interface) // public static String Final S = "AAA"; / / public abstract Test String (); // } // if custom annotations method, it is necessary to use a method by value. The method of name = value types return // notes as a container for the value of the output of the transmission to others, needs its own assignment method, when defining attribute has been assigned the notes // If only one method, a method called value can be written directly omit the method name value: for example, comes with java annotations SuppressWarnings, there is only one method String [] value (); @MyAnnotation (testInt =. 1, testString = "AAA", testStringArray = { "AAA", "BBB", "CCC" }) Private String STR; public static void main (String [] args) { the try { // application Note: the use of a reflective class C1 = annotationClass. class ; // Get class Field, F1 = c1.getDeclaredField ( "STR"); // Get property annotated according to the attribute name // get notes, analytical content MA1 = f1.getAnnotation MyAnnotation (. MyAnnotation class ); int value1_1 = ma1.testInt (); String value1_2 = ma1.testString (); String [] value1_3 = ma1.testStringArray (); System.out.println ( "VALUE1 = "+ + value1_1" value2 = "+ + value1_2" value3 [0] = "+ value1_3 [0 ]); // VALUE1 = 1value2 aaavalue3 = [0] = AAA // felt acts like a global variable. . . // completely parsed content by reflection Class C2 = annotationClass. Class ; // Get Class F2 = c2.getDeclaredField Field, ( "str"); // get the names according to the attributes annotated property Annotation MA2 = f2.getAnnotation (MyAnnotation. Class ); Class clazz2 = ma2.getClass (); Method, M2_1 = clazz2.getDeclaredMethod ( "testInt"); // generally used for convenience, only the annotations are typically inside a String [] value method, so that there can be a unitary int value2_1 = ( int ) m2_1.invoke (MA2); method, M2_2 = clazz2. getDeclaredMethod ( "testString" ); String value2_2 = (String) m2_2.invoke (MA2); Method, m2_3 = clazz2.getDeclaredMethod ( "testStringArray"); String[] value2_3 = (String[]) m2_3.invoke(ma2); System.out.println("value1 = " + value2_1 + "value2 = " + value2_2 + "value3[0] = " + value2_3[0] ); //value1 = 1value2 = aaavalue3[0] = aaa } catch (Exception e) { e.printStackTrace(); } } }

 

 

A custom annotation

Package Penalty for AnnotationTest; 

Import Classes in java.lang.annotation *. ; 

// custom annotation:
 // annotations can contain only the following types of information:
 // basic types
 // String
 // enumeration enum
 // Notes @
 // four kinds of the above type array [] 

// custom annotations @interface use, need to add annotations element (java own annotations, annotation for explaining)
 // element annotation Target, annotation may be described using the current position, which is an enum 
@Target ({ ElementType.FIELD, ElementType.METHOD, ElementType.CONSTRUCTOR})   // properties, methods, constructors 

// membered Retention annotations, describe what is present in the current annotation scope
 // source .java files - compiled - bytecode file .class --- execution - memory
 // source file: annotation is only used as an annotate the sOURCE
 //Bytecode files: compile-time use, you can detect the CLASS
 // Memory: used to perform RUNTIME 
@Retention (RetentionPolicy.RUNTIME)    // using runtime 

@ Inherited // notes can be inherited 

@Documented   // be changed to the document, not used 

// annotation interface consistent with the internal configuration of 
public @ interface MyAnnotation { 

    // may describe public static final properties, and may not write modifiers, default public static final 
    public  static  Final String S = "AAA" ; 

    // public abstract type method, there is no method body, public abstract may be omitted
     // must have a return value (interface method can be used in the void, not annotated)
     // annotated method primarily for dynamic transmission information 
    public  abstract int testInt();

    public abstract String testString();

    public abstract String[] testStringArray();
}

 

// Notes applications and advantages, look at an example: I can not read his notes written prior to reflection. . .

A simulation scenario, two development companies, A write underlayer, B generated by the underlying object A is used

He said customer suddenly one day to add attributes, A Class changed the bottom (javaBean), the number of different properties, construction methods have changed.

Where traditionally the case, B would have to put all the upper class used in this whole change again! In case this project is very large, hundreds of class, the workload will be very scary, but also easy to miss.

At this time we should use Spring's idea: IOC Inversion of Control (Creating A over to someone else, not the way to create new constructor), Di dependency injection (not a new object, and then assign the call method), so A the class structure changes will not affect B

Significantly reduce the degree of coupling, so that A modification of the effects of class B to a minimum.

 

Write a comment for stored value by value

package AnnotationTest;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.RUNTIME)
public @interface AnAnnotation {
    String[] value();
}

 

Underlying class A: The method used here @ annotation stored value, which can facilitate the development of modified time, a test class.

package AnnotationTest;



public class ObjectTest {

    private String name;
    private Integer age;
    private String sex;

    @AnAnnotation({"一个名字","24", "男"})
    public ObjectTest(){
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

 

A method for generating written B class object 

Output:

-------------- start processing properties of 0 ---------------
get set methods: setName
first property assignment: name = name
treatment started 1 -------------- --------------- properties
obtained set methods: setAge
first attribute assignment: Age = 24
- ------------- begin processing the second attribute ---------------
obtained set methods: setSex
first attribute assignment: sex = male
- ------------- Object assignment ended ------------------
name is: a name
age: 24
gender: Male

 

Want to experience the benefits of reflection, you can modify ObjectTest class

package AnnotationTest;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.text.Format;

public class AnnotationTest {
    public static void main(String[] args){
        AnnotationTest at = new AnnotationTest();
        Object obj = at.createObject("AnnotationTest.ObjectTest");
        ObjectTest objectTest = (ObjectTest)obj;// generic 
        System.out.println ( "named:" + objectTest.getName ()); 
        System.out.println ( "age:" + objectTest.getAge ()); 
        System.out.println ( "Sex It is: "+ objectTest.getSex ()); 


        // then the question came. . . What benefit is it's so dry!
        // can try ObjectTest the Class class changed a bit, such as gender and sex-related getSex, setSex method to remove, modify annotation @, the following generation object methods can still be used without modifying any code.
        // place if in the project, hundreds of class call each other each other, once a class change occurs (such as customer database to add a new field), traditional methods would have to use all objects of this class of full re-change again,
         // but you can change this class reflection only and do not change the other place.
        // This can reduce the degree of coupling between classes, ObjectTest modifying effect on AnnotationTest greatly reduced. 
    } 

    // IOC
     //Write a method, according to traditional values annotation class name using the above construction method, the object directly generate 
    public Object of createObject (String objectClassName) { 
        Object obj = null ; // Returns the object generating 
        the try { 
            Class C = the Class.forName (objectClassName ); // get the object class to generate 
            the constructor c.getConstructor = constructor (); // get constructor 

            AnAnnotation annotation = (AnAnnotation) constructor.getAnnotation (AnAnnotation. class ); // get the value of the annotation -> the attributes of the object value 
            String [] values =   annotation.value (); 

            obj = Constructor.newInstance ();// using non-parametric method of generating object constructor Object 
            Field, [] = c.getDeclaredFields Fields (); // All the properties obtained class
             // assigns them 
            for ( int I = 0; I <fields.length; I ++ ) { 
                the System .out.println ( "start treatment --------------" + i + "attributes ---------------" ); 
                Class the fieldType Fields = [I] .getType (); // get property type 

                // Get the name of the method set + set attribute names capitalized 
                String firstFieldName = Fields [I] .getName () the substring (0,1. ) .toUpperCase () ; 
                String lastFieldName . = Fields [I] .getName () the substring (. 1 );
                SetMethodName the StringBuilder = new new the StringBuilder ( "set" ); 
                setMethodName.append (firstFieldName); 
                setMethodName.append (lastFieldName); 

                System.out.println ( "get set methods:" + setMethodName); 

                Method, setMethod = c.getMethod (setMethodName. toString (), the fieldType); // with the methods set type and attribute set method to obtain 

                the constructor constructorField = fieldType.getConstructor (String. class ); // Get method parameter set type String parameter for the constructor, as values [] the values are String 

                setMethod.invoke (obj, constructorField.newInstance (values [I])); //The method of operation set, the values [] corresponding values to the corresponding method obj 
                System.out.println ( "first property assignment:" Fields + [I] .getName () + "=" + values [I ]); 
            } 

        } the catch (Exception E) { 
            e.printStackTrace (); 
        } 

        System.out.println ( "Object assignment end --------------- ------- ----------- " );
         return obj; // to create the object assignment is completed return 
    } 
}

 

Guess you like

Origin www.cnblogs.com/clamp7724/p/11667845.html