Why reflection?

Why introduce reflection when Java objects can be created with the new keyword? The new keyword is used only if you know the name of the class. If you don’t know the name, you can’t create a class by hard coding it. This is where reflex plays a big role. The purpose of reflection is to extend unknown applications

Simple use review

The implementation of reflection mechanism is dominated by three classes: Class, Field, and Method

Class

Java when to compile and run, will need to be compiled and run all the classes loaded into the Class loader, each Class is loaded, the system will generated the corresponding Class object for the Class, through the Class object can access to the Class of the JVM, then run time can pass this Class information acquisition and processing.

There are three ways to reflect objects

Start with a Java class: iuser.java

package reflex;

import lombok.ToString;

/ * * *@author zhangshuai
 */
@ToString
public class IUser {
    private Long uId;
    private String uName;
    private String password;
}

Copy the code
  • 1. Call the forName (String name) static method of Class
package reflex;

/ * * *@author zhangshuai
 */
public class Main {
    public static void main(String[] args) throws Exception { Class<? > aClass = Class.forName("reflex.IUser");
        System.out.println("Package path for this class:" + aClass.getPackage());
        System.out.println("ToString method of this class:" + aClass.getMethod("toString")); --------------------------- Package path of this class:packageReflex toString method of this class:public java.lang.String reflex.IUser.toString()
Copy the code

This approach reflects by looking for the IUser class under the package path, and the parameter name must contain the full path of name (including the package name). Reflex is the package name. Class
indicates that the Class object corresponding to the IUser type is received via generics. Class. ForName (” com.mysql.jdbc.driver “);

Source code analysis:

/**
     * Returns the {@code Class} object associated with the class or
     * interface with the given string name.  Invoking this method is
     * equivalent to:
     *
     * <blockquote>
     *  {@code Class.forName(className, true, currentLoader)}
     * </blockquote>
     *
     * where {@code currentLoader} denotes the defining class loader of
     * the current class.
     *
     * <p> For example, the following code fragment returns the
     * runtime {@code Class} descriptor for the class named
     * {@code java.lang.Thread}:
     *
     * <blockquote>
     *   {@code Class t = Class.forName("java.lang.Thread")}
     * </blockquote>
     * <p>
     * A call to {@code forName("X")} causes the class named
     * {@code X} to be initialized.
     *
     * @param      className   the fully qualified name of the desired class.
     * @return     the {@code Class} object for the class with the
     *             specified name.
     * @exception LinkageError if the linkage fails
     * @exception ExceptionInInitializerError if the initialization provoked
     *            by this method fails
     * @exception ClassNotFoundException if the class cannot be located
     */
    @CallerSensitive
    public staticClass<? > forName(String className)throws ClassNotFoundException {
        // A native method provided by the JDK to get the caller's linkClass<? > caller = Reflection.getCallerClass();// called after a security check on the system loader access check.
        return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
    }
Copy the code

Method description: Returns the Class object associated with the Class or interface with the given string name. Calling this method is equivalent to: class.forname (className, true, currentLoader) where currentLoader represents the defining classloader for the current Class. For example, the following code snippet returns the runtime Class descriptor for a Class named java.lang.thread: Class t = class.forname (” java.lang.thread “) a call to forName(“X”) causes a Class named X to be initialized

  • Call classclassProperty to get the corresponding Class object of the Class

The JVM will use the Class loader, load the Class into memory (assuming it hasn’t been loaded into memory yet), do nothing to initialize the Class, and return the Class object. That is, the resulting object is not initialized in this way, and no code or code block in the object is called during the process.

Class<? > mClass = IUser.class;Copy the code
  • Call class instantiation objectgetClass()Methods.

GetClass () is a method of the Object class, the ancestor of Java classes, so all Java objects can call this method; Such as Class
mClass = new IUser().getClass() returns the Class object corresponding to IUser

Class<? > aClass3 =new IUser().getClass();
Copy the code

The first approach is recommended because of the extensibility of fetching classes

ClassClass interface description: (Note: in the table, the corresponding Class object, let’s call it the target Class)

interface The return type Interface Function
getPackage() Package Get the Package object corresponding to the Package name of the target class
getCanonicalName() String Get the full name of the target class (package name + class name)
getName() String With getCanonicalName ()
getClassLoader() ClassLoader Gets the ClassLoader object that loads the target class
getClasses() Class<? > [] Get all the public inner classes in the target Class and the Class objects corresponding to the public inner interface
getDeclaredClasses() Class<? > [] Same as getClasses(), but not limited to the public modifier, as long as the inner class and interface are declared in the target class
getConstructors() Constructor<? > [] Gets the Constructor objects corresponding to all public constructors of the target class
getDeclaredConstructors() Constructor<? > [] Same as getConstructors(), but not limited to public, as long as the constructor is declared in the target class
getEnclosingClass() Class Gets the Class object of the enclosing Class of the target Class
getInterfaces() Class<? > [] Gets the Class object corresponding to the interface implemented by the target Class
getSuperclass() Class Gets the Class object corresponding to the parent of the target Class

Field

A Class contains properties and methods, Class describes information about the Class, and the occurrence of a Class described by Field includes public, protected, and private properties.

Interface methods

Prepare the base class: Fieldbereflartic.java

package reflex;

/ * * *@author zhangshuai
 */
public class FieldBeReflected {
    private static String name;
    protected static double mDouble;
    public static char mChar;
    int mInt;
}

Copy the code
  • getField(String name): The return type isField,name is the name of the property in the class, the resulting description of a public property in the class corresponding to the Field object;
package reflex;

import java.lang.reflect.Field;

/ * * *@author zhangshuai
 */
public class Main {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        / / classClass<? > mClass = Class.forName("reflex.FieldBeReflected");
        / / properties
// Field name = mClass.getField("name"); // NoSuchFieldException
// Field mDouble = mClass.getField("mDouble"); // NoSuchFieldException
// Field mInt = mClass.getField("mInt"); // NoSuchFieldException
        Field mChar = mClass.getField("mChar");
        System.out.println(mChar); //public static char reflex.FieldBeReflected.mChar}}Copy the code

Thus, the getField(String Name) method can only get properties that are public

Source code analysis:


    /**
     * Returns a {@code Field} object that reflects the specified public member
     * field of the class or interface represented by this {@code Class}
     * object. The {@code name} parameter is a {@codeString} specifying the * simple name of the desired field. * * <p> The field to be reflected is determined by the algorithm that * follows. Let C be the class or interface represented by this object: * * <OL> * <LI> If C declares a public field with the name specified, that is the * field to be reflected.</LI> * <LI> If no field was found in step 1 above, this algorithm is applied * recursively to each direct superinterface of C. The direct * superinterfaces are searched in  the order they were declared.</LI> * <LI> If no field was found in steps 1 and 2 above, and C has a * superclass S, then this algorithm is invoked recursively upon S. * If C has no superclass, then a {@code NoSuchFieldException}
     *      is thrown.</LI>
     * </OL>
     *
     * <p> If this {@code Class} object represents an array type, then this
     * method does not find the {@code length} field of the array type.
     *
     * @param name the field name
     * @return the {@code Field} object of this class specified by
     *         {@code name}
     * @throws NoSuchFieldException if a field with the specified name is
     *         not found.
     * @throws NullPointerException if {@code name} is {@code null}
     * @throwsSecurityException * If a security manager, <i>s</i>, is present and * the caller's class loader is not the same as or an * ancestor of the class loader for the current class  and * invocation of {@link SecurityManager#checkPackageAccess
     *         s.checkPackageAccess()} denies access to the package
     *         of this class.
     *
     * @since JDK1.1
     * @jls8.2 the Class Members@jls8.3 the Field Declarations * /
     
    @CallerSensitive
    public Field getField(String name)
        throws NoSuchFieldException, SecurityException {
        // Perform security check to check whether the operation has permission. If not, throw a SecurityException
        // Default policy: allow all clients to use normal Java access control
        checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
        // Search the public property of all fields
        Field field = getField0(name);
        if (field == null) {
            throw new NoSuchFieldException(name);
        }
        return field;
    }

Copy the code

Returns a Field object that reflects the specified public member Field of the Class or interface represented by this Class object. The name argument is a String specifying the simple name of the desired field. The field to be reflected is determined by the following algorithm. Let C be the class or interface that the object represents: If C declares a public field with a specified name, that is the field to reflect. If no fields are found in step 1 above, the algorithm recursively applies to each direct hyperinterface of C. Direct superinterfaces search in the order in which they are declared. If no fields are found in steps 1 and 2 above, and C has a superclass S, then the algorithm is called recursively on S. If C has no superclass, a NoSuchFieldException is thrown. If this Class object represents an array type, this method cannot find the Length field of the array type. Throw: NoSuchFieldException – if no field with the specified name was found. NullPointerException – If name is null; SecurityException – If there is a security manager s and the caller has a class loader that is different from or not a ancestor of the current class, and s.checkPackageAccess() is called to deny access to the package for that class

  • getFields(): Returns an array of type Field that describes all fields corresponding to all public attributes in the class
package reflex;

import java.lang.reflect.Field;

/ * * *@author zhangshuai
 */
public class Main {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        / / classClass<? > mClass = Class.forName("reflex.FieldBeReflected");
        / / properties
        Field[] fields = mClass.getFields();
        for(Field field : fields) { System.out.println(field); }}} -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --public static char reflex.FieldBeReflected.mChar
Copy the code

Like the getField(String name) method, the getFields() method can only take a public-decorated array of fields

Source code analysis:

 /**
     * Returns an array containing {@code Field} objects reflecting all
     * the accessible public fields of the class or interface represented by
     * this {@code Class} object.
     *
     * <p> If this {@code Class} object represents a class or interface with no
     * no accessible public fields, then this method returns an array of length
     * 0.
     *
     * <p> If this {@code Class} object represents a class, then this method
     * returns the public fields of the class and of all its superclasses.
     *
     * <p> If this {@code Class} object represents an interface, then this
     * method returns the fields of the interface and of all its
     * superinterfaces.
     *
     * <p> If this {@code Class} object represents an array type, a primitive
     * type, or void, then this method returns an array of length 0.
     *
     * <p> The elements in the returned array are not sorted and are not in any
     * particular order.
     *
     * @return the array of {@code Field} objects representing the
     *         public fields
     * @throwsSecurityException * If a security manager, <i>s</i>, is present and * the caller's class loader is not the same as or an * ancestor of the class loader for the current class  and * invocation of {@link SecurityManager#checkPackageAccess
     *         s.checkPackageAccess()} denies access to the package
     *         of this class.
     *
     * @since JDK1.1
     * @jls8.2 the Class Members@jls8.3 the Field Declarations * /
    @CallerSensitive
    public Field[] getFields() throws SecurityException {
        // Perform security check to check whether the operation has permission. If not, throw a SecurityException
        // Default policy: allow all clients to use normal Java access control
        checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
        // Copy the reproducible Field properties of this class through the ReflectionFactory's copyField method
        return copyFields(privateGetPublicFields(null));
    }
Copy the code

First, this method starts with jdk1.1, which means that it returns an array of Field objects that reflect the Class of the interface represented by the Class object or any accessible public fields of the interface. If the Class object does not have a Class or interface that can access a public field, an array of length 0 is returned; If the Class object represents a Class, the public fields of that Class and all its superclasses are returned; If the Class object represents an interface, the public fields of that interface and all of its superinterfaces are returned; If the Class object is an array type, primitive type, or void, return an array of length 0; Returns that there is no particular sort in the array type and that the method throws a SecurityException

  • getDeclaredField(String name)With:getField(String name)The resulting Field object describes not only public properties, but also protected and private properties, as long as the property is declared in the class.
package reflex;

import java.lang.reflect.Field;

/ * * *@author zhangshuai
 */
public class Main {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        / / classClass<? > mClass = Class.forName("reflex.FieldBeReflected");
        / / properties
        Field name = mClass.getDeclaredField("name");
        Field mDouble = mClass.getDeclaredField("mDouble");
        Field mInt = mClass.getDeclaredField("mInt");
        Field mChar = mClass.getDeclaredField("mChar"); System.out.println(name); System.out.println(mDouble); System.out.println(mInt); System.out.println(mChar); }} -- -- -- -- -- -- -- -- -- -- -- --private static java.lang.String reflex.FieldBeReflected.name
protected static double reflex.FieldBeReflected.mDouble
int reflex.FieldBeReflected.mInt
public static char reflex.FieldBeReflected.mChar
Copy the code

This method gets all the attributes of the Class

Source code analysis:


    /**
     * Returns a {@code Field} object that reflects the specified declared
     * field of the class or interface represented by this {@code Class}
     * object. The {@code name} parameter is a {@code String} that specifies
     * the simple name of the desired field.
     *
     * <p> If this {@code Class} object represents an array type, then this
     * method does not find the {@code length} field of the array type.
     *
     * @param name the name of the field
     * @return  the {@code Field} object for the specified field in this
     *          class
     * @throws  NoSuchFieldException if a field with the specified name is
     *          not found.
     * @throws  NullPointerException if {@code name} is {@code null}
     * @throws  SecurityException
     *          If a security manager, <i>s</i>, is present and any of the
     *          following conditions is met:
     *
     *          <ul>
     *
     *          <li> the caller's class loader is not the same as the
     *          class loader of this class and invocation of
     *          {@link SecurityManager#checkPermission
     *          s.checkPermission} method with
     *          {@code RuntimePermission("accessDeclaredMembers")}
     *          denies access to the declared field
     *
     *          <li> the caller's class loader is not the same as or an
     *          ancestor of the class loader for the current class and
     *          invocation of {@link SecurityManager#checkPackageAccess
     *          s.checkPackageAccess()} denies access to the package
     *          of this class
     *
     *          </ul>
     *
     * @since JDK1.1
     * @jls8.2 the Class Members@jls8.3 the Field Declarations * /
    @CallerSensitive
    public Field getDeclaredField(String name)
        throws NoSuchFieldException, SecurityException {
        Unlike getField (String name), this method does not get the attributes of the parent class or interface
        checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
        Field field = searchFields(privateGetDeclaredFields(false), name);
        if (field == null) {
            throw new NoSuchFieldException(name);
        }
        return field;
    }
Copy the code

Returns a Field object that reflects the specified declaration Field of the Class or interface represented by this Class object. The name argument is a String that specifies the simple name of the desired field. If this Class object represents an array type, this method cannot find the Length field of the array type. This method also throws NoSuchFieldException, NullPointerException, and SecurityException

  • getDeclaredFields(): getFields(), which describes all the fields (public, protected, private) declared in the class;
package reflex;

import java.lang.reflect.Field;

/ * * *@author zhangshuai
 */
public class Main {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        / / classClass<? > mClass = Class.forName("reflex.FieldBeReflected");
        / / properties
        Field[] fields = mClass.getDeclaredFields();
        for(Field field : fields) { System.out.println(field); }}} -- -- -- -- -- -private static java.lang.String reflex.FieldBeReflected.name
protected static double reflex.FieldBeReflected.mDouble
public static char reflex.FieldBeReflected.mChar
int reflex.FieldBeReflected.mInt
Copy the code

Returns all fields of this class, excluding superclasses

Source code analysis:



    /**
     * Returns an array of {@code Field} objects reflecting all the fields
     * declared by the class or interface represented by this
     * {@code Class} object. This includes public, protected, default
     * (package) access, and private fields, but excludes inherited fields.
     *
     * <p> If this {@code Class} object represents a class or interface with no
     * declared fields, then this method returns an array of length 0.
     *
     * <p> If this {@code Class} object represents an array type, a primitive
     * type, or void, then this method returns an array of length 0.
     *
     * <p> The elements in the returned array are not sorted and are not in any
     * particular order.
     *
     * @return  the array of {@code Field} objects representing all the
     *          declared fields of this class
     * @throws  SecurityException
     *          If a security manager, <i>s</i>, is present and any of the
     *          following conditions is met:
     *
     *          <ul>
     *
     *          <li> the caller's class loader is not the same as the
     *          class loader of this class and invocation of
     *          {@link SecurityManager#checkPermission
     *          s.checkPermission} method with
     *          {@code RuntimePermission("accessDeclaredMembers")}
     *          denies access to the declared fields within this class
     *
     *          <li> the caller's class loader is not the same as or an
     *          ancestor of the class loader for the current class and
     *          invocation of {@link SecurityManager#checkPackageAccess
     *          s.checkPackageAccess()} denies access to the package
     *          of this class
     *
     *          </ul>
     *
     * @since JDK1.1
     * @jls8.2 the Class Members@jls8.3 the Field Declarations * /
    @CallerSensitive
    public Field[] getDeclaredFields() throws SecurityException {
        checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
        return copyFields(privateGetDeclaredFields(false));
    }
Copy the code

Like the getFields() method, the only difference is that it cannot accept fields from a parent or superclass: it returns an array of Field objects that reflect all the fields declared by the Class or interface represented by the Class object. This includes public, protected, default (package) access, and private fields, but does not include inherited fields. If this Class object represents a Class or interface that has no declared fields, this method returns an array of length 0. If the Class object represents an array type, a primitive type, or void, this method returns an array of length 0. The elements of the returned array are not sorted or in any particular order

Use Feild

package reflex;

import java.lang.reflect.Field;
import java.lang.reflect.Type;


public class ReflectField {

    public static void main(String[] args) {
        /* 1.Class
       clazz = Class.forName("com.stevenhu.field.FieldBeReflected"); * 2.Class
       clazz = new FieldBeReflected().getClass(); * /Class<? > clazz = FieldBeReflected.class;try {
            Field fName = clazz.getDeclaredField("name");
            Field fBoolean = clazz.getDeclaredField("mBoolean");
            Field fByte = clazz.getDeclaredField("mByte");
            Field fShort = clazz.getDeclaredField("mShort");
            Field fInt = clazz.getDeclaredField("mInt");
            Field fLong = clazz.getDeclaredField("mLong");
            Field fFloat = clazz.getDeclaredField("mFloat");
            Field fDouble = clazz.getDeclaredField("mDouble");
            Field fChar = clazz.getDeclaredField("mChar");

            If * is false, the reflected class and the reflected class are in the same package, and the private and protected object properties are not in the same package
            fName.setAccessible(true);

            /* Set the value for the target property (the private property is not accessible, but can be accessed by calling setAccessible(true) first), * Since the name property in the ReflectField class is static, So the first argument to the method is passed in clazz, the Class object corresponding to the target attribute, or clazz.newinstance (); * /
            fName.set(clazz, "reflection");
            // Get the value of the target property (private property is not accessible, but can be accessed by calling setAccessible(true))
            String name = (String) fName.get(clazz);
            System.out.println(name);

            fBoolean.setAccessible(true);
            /* Gets the Boolean value for the target attribute. Since the mBoolean attribute in the ReflectField class is non-static, * the argument passed here is the instance of the class where the target attribute resides clazz.newinstance () */
            boolean mBoolean = fBoolean.getBoolean(clazz.newInstance());
            System.out.println(mBoolean);

            fByte.setAccessible(true);
            // Get the Byte value of the target attribute
            byte mByte = fByte.getByte(clazz.newInstance());
            System.out.println(mByte);

            fShort.setAccessible(true);
            // Get the short value of the target property
            short mShort = fShort.getShort(clazz);
            System.out.println(mShort);

            fInt.setAccessible(true);
            // Set the target property to an integer value
            fInt.setInt(clazz, 222);
            // Get the integer value of the target attribute
            int mInt = fInt.getInt(clazz);
            System.out.println(mInt);

            fLong.setAccessible(true);
            // Set the target property to a Long integer value
            fLong.setLong(clazz, 2222);
            // Get the target property's Long integer value
            Long mLong = fLong.getLong(clazz);
            System.out.println(mLong);

            fFloat.setAccessible(true);
            // Set the target property to a float value
            fFloat.setFloat(clazz, 22222);
            // Get a float value for the target property
            float mFloat = fFloat.getFloat(clazz);
            System.out.println(mFloat);

            fDouble.setAccessible(true);
            // Set the target property to a double value
            fDouble.setDouble(clazz, 222.222);
            // Get the target property's double value
            double mDouble = fDouble.getDouble(clazz);
            System.out.println(mDouble);

            // Set character values for target properties (private and protected properties are not accessible)
            fChar.setChar(clazz, 'a');
            // Get the character value of the target property (private and protected properties are not accessible)
            char mChar = fChar.getChar(clazz);
            System.out.println(mChar);

            // The name of the target property, not limited to modifiers, as long as the property is declared in the class
            String name1 = fName.getName();
            System.out.println(name1);
            // The type of the target attribute, not limited to modifiers
            Type type = fName.getGenericType();
            System.out.println(type);
            // The type of the target attribute corresponds to the Class objectClass<? > clazz1 = fName.getType(); System.out.println(clazz1);// The Class object corresponding to the target attributeClass<? > clazz2 = fName.getDeclaringClass(); System.out.println(clazz2);// The permission modifier value of the target property (private is 2, protected is 4, public is 1)
            int modifier = fName.getModifiers();
            int modifier1 = fByte.getModifiers();
            int modifier2 = fShort.getModifiers();
            System.out.println(modifier);
            System.out.println(modifier1);
            System.out.println(modifier2);

            System.out.println(fName.isAccessible());
            System.out.println(fChar.isAccessible());

        } catch(NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException | InstantiationException e) { e.printStackTrace(); }}}Copy the code

Method

Like Field, a Method object describes the methods of a class

Interface methods

  • getMethod(String name, Class
    … ParameterTypes: returns Method. The first parameter is the name of the Method in the Class. The second parameter is a variable parameter. This function returns a Method object that describes a public Method in the class.

  • GetMethods () : Returns an array of Method types that describe all public methods in the class.

  • Method getDeclaredMethod(String name, Class
    … ParameterTypes: same as getMethod(String name, Class
    … ParameterTypes are not only public methods but also protected and private methods, as long as they are declared in classes.

  • GetDeclaredMethods () : getMethods(), which describes all methods declared in the class (public, protected, private) corresponding to FMethod object;

Method using

package reflex;

public class MethodBeReflected {

    private static String mName;
    private static int mAge;
    private static float mWeight;

    private String getmName(a) {
        return mName;
    }

    protected void setmName(String mName) {
        this.mName = mName;
    }

    protected static int getmAge(a) {
        return mAge;
    }

    private static void setmAge(int age) {
        mAge = age;
    }

    private float getmWeight(a) {
        return mWeight;
    }

    protected void setmWeight(float mWeight) {
        this.mWeight = mWeight;
    }

    private void setAllValues(String name, int age, float weight) {
        this.mName = name;
        this.mAge = age;
        this.mWeight = weight; }}Copy the code
package reflex;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;


public class ReflectMethod {
    public static void main(String[] args) { Class<? > clazz = MethodBeReflected.class;try {
            // The first argument is the method name, and the second argument is the class object corresponding to the method parameter type
            Method nameMethod = clazz.getDeclaredMethod("setmName", String.class);
            Method ageMethod = clazz.getDeclaredMethod("setmAge".int.class);
            Method weightMethod = clazz.getDeclaredMethod("setmWeight".float.class);
            Method allValuesMethod = clazz.getDeclaredMethod("setAllValues", String.class, int.class, float.class);

            nameMethod.setAccessible(true);
            // Call the setmName method and assign the attribute mName in the ReflectMethod class to "stevenhu"
            nameMethod.invoke(clazz.newInstance(), "lisa");
            nameMethod = clazz.getDeclaredMethod("getmName");
            nameMethod.setAccessible(true);
            // Call getmName to get the value of mName
            String name1 = (String) nameMethod.invoke(clazz.newInstance());
            System.out.println(name1);

            ageMethod.setAccessible(true);
            /* Call setmAge to set the age. Since this method is static, the first argument can be clazz or clazz.newinstance (); * /
            ageMethod.invoke(clazz, 21);
            ageMethod = clazz.getDeclaredMethod("getmAge");
            ageMethod.setAccessible(true);
            // Call getmAge to get the age set earlier
            int age1 = (Integer) ageMethod.invoke(clazz);
            System.out.println(age1);

            weightMethod.setAccessible(true);
            // Call the setmWeight method to set the weight
            weightMethod.invoke(clazz.newInstance(), 50.5 F);
            weightMethod = clazz.getDeclaredMethod("getmWeight");
            weightMethod.setAccessible(true);
            // Call getmWeight to get the body age set earlier
            float weight1 = (Float) weightMethod.invoke(clazz.newInstance());
            System.out.println(weight1);

            allValuesMethod.setAccessible(true);
            /* Call the setAllValues method of ReflectMethod to assign a value * Note: The argument 63.5 cannot be passed directly; Floating-point must create Float * Integer and String. Integer, String, or */ may not be created
            allValuesMethod.invoke(clazz.newInstance(), "stevenhu".23.63.5 F);

            nameMethod = clazz.getDeclaredMethod("getmName");
            nameMethod.setAccessible(true);
            String name2 = (String) nameMethod.invoke(clazz.newInstance());
            System.out.println(name2);

            ageMethod = clazz.getDeclaredMethod("getmAge");
            ageMethod.setAccessible(true);
            int age2 = (Integer) ageMethod.invoke(clazz.newInstance());
            System.out.println(age2);

            weightMethod = clazz.getDeclaredMethod("getmWeight");
            weightMethod.setAccessible(true);
            float weight2 = (Float) weightMethod.invoke(clazz.newInstance());
            System.out.println(weight2);

            // Get the Class object corresponding to the target methodClass<? > clazz1 = weightMethod.getDeclaringClass();// Get the Class object corresponding to the type of exception thrown by the target methodClass<? >[] clazzs1 = weightMethod.getExceptionTypes();for(Class<? > cl : clazzs1) { System.out.println(cl); }// Get the Type object corresponding to the exception Type thrown by the target method
            Type[] types1 = weightMethod.getGenericExceptionTypes();
            // Get the Class object corresponding to the return type of the target methodClass<? > clazz2 = nameMethod.getReturnType();// Get the Type object corresponding to the return Type of the target method
            Type type = nameMethod.getGenericReturnType();
            // Get the Class object corresponding to each parameter type of the target methodClass<? >[] clazzs2 = allValuesMethod.getParameterTypes();// Get the Type object corresponding to each parameter Type of the target method
            Type[] types2 = allValuesMethod.getGenericParameterTypes();
            // Get the value of the target method modifier
            int modifier = ageMethod.getModifiers();
            System.out.println(modifier);
            // Get the target method name
            String methodName = nameMethod.getName();
            System.out.println(nameMethod.isVarArgs());
        } catch(NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException e) { e.printStackTrace(); }}}Copy the code

Frequently seen exam

1. What is reflection

Concept: In the running state, all properties and methods of any class can be known; And for any object can call any of its methods, this dynamic access to information and dynamic call object method function is called Java reflection mechanism; Understanding: Get information about classes, fields, methods from bytecode files, and can create instances and call method techniques.

2. What are the scenes of reflection

JDBC original code registration driver, Spring Bean loading process, Spring AOP, Tomcat loading Servlet process;

Reflection and class

In the running state of the program, you can know all the properties and methods of any class (i.e. the.class file).

4. Reflection and class object relationship

Reflection Can call any of its methods and properties on an object of a class.

5. Pros and cons of reflection

Reflection greatly improves application extensibility; Reflection is used to improve program extensibility through polymorphism, passing subclass objects to parent class references. For example: Animal dog = new dog (); This way has a big weakness is must establish the subclass object, by the new keyword subclass object must write a death in the code, and through reflection technology to omit the new subclass object step directly to subclass object class name in the form of a string is passed to the reflection technology framework, and to the reflection technology to create this string represents the instance of tired.

6. Two ways to create objects

  • NewInstance () uses the newInstance() method of the Class object to create instances of the corresponding Class, but this method requires that the corresponding Class have a default empty constructor.

  • Calling newInstance() to the Constructor object first uses the Class object to get the specified Constructor object, The newInstance() method of the Constructor object is then called to create an instance of the corresponding Class of the Class object, using which you can select the Constructor to create the instance.