Call of reflected fields, methods and constructors (2)

Author: Sannian

Call of reflected fields, methods and constructors (2)

This paper continues with the previous article: the concept of reflection and acquisition methods (1) Click to jump

1.Class type - type of class

Get type object
1. Class.forname (full class name)
2. class name
3. Object. getClass()

common method
getName() gets the full class name
getSimpleName() gets the simple class name
getDeclaredFields() gets all the properties in the class
getDeclaredMethods() gets all methods in the class
getDeclaredConstructors() gets all constructors in the class
newInstance() instantiates the object of the class (open nonparametric construction)

2.Field type - type of property

common method
getName() gets the property name
getType() gets the type of the property
get(Object obj) gets the value of this property in the obj object
set(Object obj, Object value) sets the value of this property in the obj object to value
setAccessible(true) allow access

package com.sannian;

import java.lang.reflect.Field;

public class Demo01 {
    public static void main(String[] args) {
/*******************  Use fields*************************/
        try {
            Class<?> c = Class.forName("com.sannian.Student");
            /**Construction object*/
            Object student = c.newInstance();
                //Output: com.sannian.Student
//          System.out.println(student.getClass().getName());

        /**Set name field*/
            /**Take out the object of name*/
            Field name = c.getField("name");
            /**Put Zhang San in the name field of the student object*/
            name.set(student, "Zhang San");
            /**Get the name field of the student object*/
            Object obj = name.get(student);
            //Output: Zhang San
            System.out.println(obj);

        /**Set age field*/
            Field age = c.getField("age");
            age.set(student, 18);
            /**Take out age field and print*/
            System.out.println(age.get(student));

        /**Set private money field*/
            Field money = c.getDeclaredField("money");
            money.setAccessible(true);
            money.set(student, 100);
            System.out.println(money.get(student));

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }

    }
}

3.Method type - method type

common method
getName() get method name
getReturnType() gets the return value type
invoke(Object obj, Object… args) call this method of obj object. The parameter list is args
getTypeParameters() get parameter list

package com.sannian;

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

public class Demo03 {
    /*******************  Calling methods through reflection*************************/
    public static void main(String[] args) {
        try {
            Class<?> c = Class.forName("com.sannian.Student");
            Object student = c.newInstance();

            /**Get the introduction method, no parameters, no return value*/
            Method introduce = c.getMethod("introduce", null);
            introduce.invoke(student, null);

            /**Get the say method with a String parameter and no return value*/
            Method say = c.getMethod("say", String.class);
            say.invoke(student, "Method called with radiation");

            /**Get the add method with 2 int parameters and an int return value*/
//          Method add = c.getMethod("add", int.class,int.class); / / write method 1
            Method add = c.getMethod("add", new Class[]{int.class,int.class});//Style 1
            Object obj = add.invoke(student, 1,2);
//          Object obj = add.invoke(null, 1,2); / / no object is passed in because of static
            System.out.println(obj);

            /**Get private play method*/
            Method play = c.getDeclaredMethod("play", null);
            play.setAccessible(true);
            play.invoke(student, null);


        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }
}
package com.sannian;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;

public class Demo04 {
    public static void main(String[] args) {
        try {
            Class<?> c = Class.forName("com.sannian.Student");
            //Read all constructors
            Constructor<?>[] constructors = c.getConstructors();
            for (int i = 0; i < constructors.length; i++) {
                String modi = Modifier.toString(constructors[i].getModifiers());

                String list = "(";
                Class<?>[] parameterTypes = constructors[i].getParameterTypes();
                for (int j = 0; j < parameterTypes.length; j++) {
                    list += parameterTypes[j].getSimpleName();
                    if(j < parameterTypes.length - 1) {
                        list += ",";
                    }
                }
                list += ")";

                System.out.println(modi + " " + c.getSimpleName() + " " + list);
            }
            //Call separately
            //1.Nonparametric structure
//          Object o1 = c.newInstance();
            Constructor<?> con0 = c.getConstructor();
            Object obj1 = con0.newInstance();

            //2.Parametrical structure
            Constructor<?> con1 = c.getConstructor(String.class);
            Object obj2 = con1.newInstance("Zhang San");

            //3.2Parameter construction
            Constructor<?> con2 = c.getConstructor(String.class,int.class);
            Object obj3 = con2.newInstance("Li Si",18);

            System.out.println(obj1);
            System.out.println(obj2);
            System.out.println(obj3);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Keywords: Java

Added by jonez on Fri, 01 May 2020 18:50:20 +0300