Implementation of Java reflection mechanism

  • 2020-04-01 01:56:04
  • OfStack

Many mainstream frameworks use reflection technology. For example, SSH framework adopts two technologies: XML as configuration file + reflection technology.


Class packages related to reflection.

Java. Lang. Reflect. *; And Java. Lang. Class;


All types in Java (including primitive types) correspond to a Class object, which is java.lang.class. That is, for each type, there is a Class object in the Class corresponding to it. Notice there's not none, there's no public.


How do I get a Class object


. For each object .getCalss(), I can get the corresponding Class.
.Class.forName(String),String The writing of : The package name . The name of the class . The package name is created . The object to which the class name corresponds 
 Note: 1.2 Applies only to reference types 
. For basic types: wrapper classes .TYPE Represents the corresponding primitive type Class object .Integer.TYPE The corresponding is int the Class object 
 Note: 3 Only for basic types 
. type ,Class . < The first 4 Species are universal .>
 The above 4 methods , Only way to 2 Is dynamic , Just change a bag . It has dynamic potential . So the real meaning of dynamic programming is to use methods 2.

There is only one Class object of each type, that is, they have only one address, but different types are different.

So all the printouts below are true.


//Pair and reference types
Class c1 = "".getClass();
Class c2 =     Class.forName("java.lang.String");
Class c3 = String.class;
System.out.println(c1 ==c2);//true
//For basic types
Class num1 = Integer.TYPE;
Class num2 = int.class;
System.out.println(num1 == num2);//true

Reflection retrieves the associated methods for members in a class

[gets construction < by parameter type >] (usually used without declaration)


Constructor<T> getConstructor(Class<?>... parameterTypes) 
       Returns a  Constructor  Object that reflects this  Class  The specified public constructor for the class represented by the object.  
 Constructor<?>[] getConstructors() 
       Returns a containing some  Constructor  An array of objects that reflect this  Class  All public constructors of the class represented by the object.  
 Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) 
       Returns a  Constructor  Object that reflects this  Class  The specified constructor for the class or interface represented by the object.  
 Constructor<?>[] getDeclaredConstructors() 
       return  Constructor  An array of objects that reflect this  Class  Object representation of the class declaration of all constructors. 

[gets attribute < by attribute name >] (generally used with declared, because properties are generally private)

Field getField(String name) 
       Returns a  Field  Object that reflects this  Class  The specified public member field of the class or interface represented by the object.  
 Field[] getFields() 
       Returns a containing some  Field  An array of objects that reflect this  Class  All accessible public fields of the class or interface represented by the object.  
 Field getDeclaredField(String name) 
       Returns a  Field  Object that reflects this  Class  The specified declared field of the class or interface represented by the object.  
 Field[] getDeclaredFields() 
       return  Field  An array of objects that reflect this  Class  All fields declared by the class or interface represented by the object. 

[gets method < method name plus parameter type >] (usually used without declaration)

Method getMethod(String name, Class<?>... parameterTypes) 
       Returns a  Method  Object that reflects this  Class  The specified public member method of the class or interface represented by the object.  
 Method[] getMethods() 
       Returns a containing some  Method  An array of objects that reflect this  Class  The public of the classes or interfaces represented by the object, including those declared by the class or interface and those inherited from the superclass and superinterface  member  Methods.  
 Method getDeclaredMethod(String name, Class<?>... parameterTypes) 
       Returns a  Method  Object that reflects this  Class  The specified declared method of the class or interface represented by the object.  
 Method[] getDeclaredMethods() 
       return  Method  An array of objects that reflect this  Class  All methods declared by a class or interface represented by an object, including public, protected, default (package) access, and private methods, but not inherited methods.  
 T newInstance() 
       To create this  Class  A new instance of the class represented by the object.  <new Instance() Objects can be created dynamically >
 String toString() 
       Converts an object to a string. 

Note:

New Instance() calls a no-argument construct, and newInstance() generates an exception if the class has no no-argument constructor.

Declared methods support private, but not inheritance. Undeclared methods support inheritance, not private, and can only take things that are public.

So properties are generally declared when they are taken, because properties are generally private, methods are generally taken without declaration, and constructs are generally taken without declaration.

Example mock reflection retrieves the relevant properties and methods in the class

Attributes are assigned using reflection

Methods in Field

  The Object get (Object obj)

  Returns the value of the Field represented by this Field on the specified object.

          Field f = c.getxxfield (attribute name);

          Value = f.et (object);

  Void set(Object obj, Object value)

  Sets the Field represented by this Field object on the specified object variable to the specified new value.

  F. et(object, value);

  Class< ? > GetType ()

  Returns a Class object that identifies the declaration type of the Field represented by the Field object.

          The type used to get the attribute (returns the Class object).


Class c = Student.class;
    Object obj  = c.newInstance();            //Create an object for the Student class
    Field f = c.getDeclaredField("name");        //Get the name attribute
    f.setAccessible(true);                    //Set private to be accessible.
    f.set(obj, "zhangsan");
    System.out.println(f.get(obj));             //Gets the value of the name attribute of obj.

Invoke constructs using reflection

The actual call to the construct is when the newInstance() method is called.


Class c = Class.forName("com.clazz.reflect.Student");
    Constructor con = c.getConstructor();         //No execute construct,
    Object cObj = c.getConstructor().newInstance();//Invokes the argument - free constructor
    Constructor conAll = c.getConstructor(int.class,String.class,int.class);
    Object caobj = conAll.newInstance(1001,"zjamgs",234235);//Invokes the argument - containing constructor.
    System.out.println(caobj);                  //A printout

Invoke methods using reflection

Object. Method name (value 1,2,3);

Method m = c.methoed (Method name, parameter type...) ;

If the shape parameter required by the underlying method is 0, the supplied args array length can be 0 or null.


Class c = Class.forName("com.clazz.reflect.Student");
    Object obj = c.newInstance();    //Create the Sutdent object.
    Method msetName = c.getMethod("setName", String.class);//Obj does not need to convert types
    msetName.invoke(obj, "zhangsan");//Call the method setName and pass the arguments.
    Method msetId = c.getMethod("setId", int.class);
    msetId.invoke(obj, 409090202);
    System.out.println(obj);

Reflection application example

Entity class


package org.dennisit.reflect.entity;
import java.io.Serializable;
/**
 *
 *  User.java    
 *
 *  @version  :  1.1
 *  
 *  @author   :   Su Re years     <a href="mailto:DennisIT@163.com"> Send E-mail </a>
 *    
 *  @since      :  1.0         Creation time :    2013-2-26         In the afternoon 01:43:56
 *     
 *  TODO     :    class User.java is used for ...
 *
 */
public class User implements Serializable{
    private String test;

    public void execute(String name,int age){
        System.out.println("name=" + name + ",age=" + age);
    }
}

Reflection test class

package org.dennisit.reflect.main;
import java.lang.reflect.Field;
/**
 *
 *  ReflectEx.java    
 *
 *  @version  :  1.1
 *  
 *  @author   :   Su Re years     <a href="mailto:DennisIT@163.com"> Send E-mail </a>
 *    
 *  @since      :  1.0         Creation time :    2013-2-26         In the afternoon 01:46:00
 *     
 *  TODO     :    class ReflectEx.java is used for ...
 *
 */
public class ReflectEx {
    public static void main(String[] args)throws Exception {
        Class cls = Class.forName("org.dennisit.reflect.entity.User");
        Object obj = cls.newInstance();       //The object that creates the User
        Field f = cls.getDeclaredField("test");    //Get the test attribute
        f.setAccessible(true);                    //Open access to the private property test
        f.set(obj, "zhangsan");                    //Recopy for test
        System.out.println(f.get(obj));            //Gets the value of the test attribute of obj
        //Get the method by the method name execute
        java.lang.reflect.Method m = cls.getMethod("execute", String.class, int.class);
        m.invoke(obj, "dennisit",23);            //Call the execute method
    }
}

Running effect

zhangsan
name=dennisit,age=23

Write an example of a reflection dynamic instantiation class

package org.dennisit.reflect.main;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;
/**
 *
 *  DynamicReflect.java    
 *
 *  @version  :  1.1
 *  
 *  @author   :   Su Re years     <a href="mailto:DennisIT@163.com"> Send E-mail </a>
 *    
 *  @since      :  1.0         Creation time :    2013-2-26         In the afternoon 01:58:12
 *     
 *  TODO     :     Examples of dynamic instantiation using reflection 
 *
 */
public class DynamicReflect {
    public static Object getInstance(String className,Map<String,Object> map)throws Exception{
        Class c = Class.forName(className);
        Object obj = c.newInstance();                //Object the object
        Set<String> keys = map.keySet();            //Gets all the corresponding properties
        Field[] fAll = c.getDeclaredFields();        //Gets all the properties in the class
        for(int i=0;i<fAll.length;i++){
            for(String key:keys){                    //Loop matching
                if(fAll[i].getName().equals(key)){    //If the user passes in a property that matches the property name in the obtained class
                    Field f = c.getDeclaredField(key);//Get the property
                    //Build the setXxx() method name
                    String methodName = "set" + key.substring(0,1).toUpperCase()+key.substring(1);
                    Method method = c.getMethod(methodName, f.getType());//Get the corresponding method based on the user name of the build
                    method.invoke(obj, map.get(key));//The method call
                }else{
                    continue;
                }
            }
        }
        return obj;
    }
}

Next we'll test the dynamic reflection instantiation example we wrote

Entity class


package org.dennisit.reflect.entity;
import java.io.Serializable;
/**
 *
 *  User.java    
 *
 *  @version  :  1.1
 *  
 *  @author   :   Su Re years     <a href="mailto:DennisIT@163.com"> Send E-mail </a>
 *    
 *  @since      :  1.0         Creation time :    2013-2-26         In the afternoon 01:43:56
 *     
 *  TODO     :     Entity class 
 *
 */
public class User implements Serializable{
    private String name;
    private int age;
    private String email;

    public User() {  //There must be no reference structure

    }
    //getter() and setter()    

}

The main test class

package org.dennisit.reflect.main;
import java.util.HashMap;
import java.util.Map;
import org.dennisit.reflect.entity.User;
/**
 *
 *  ReflectEx.java    
 *
 *  @version  :  1.1
 *  
 *  @author   :   Su Re years     <a href="mailto:DennisIT@163.com"> Send E-mail </a>
 *    
 *  @since      :  1.0         Creation time :    2013-2-26         In the afternoon 01:46:00
 *     
 *  TODO     :    class ReflectEx.java is used for ...
 *
 */
public class ReflectEx {
    public static void main(String[] args)throws Exception {
        Class cls = Class.forName("org.dennisit.reflect.entity.User");
        String className = "org.dennisit.reflect.entity.User";
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("name", "dennisit");
        map.put("age", 22);
        map.put("email", "dennisit@163.com");

        User user = (User)DynamicReflect.getInstance(className, map);
        System.out.println(user.getName() + "," + user.getAge() + "," + user.getEmail());
    }
}

Program running result

dennisit,22,dennisit@163.com


Related articles: