java reflex - Acquisition and invocation methods

Keywords: Java

A method of obtaining a class

  1. Find the bytecode object of the class where the fetch method resides
  2. Find the method to be acquired

    Class class commonly used methods:
    1.public Method[] getMethods(); // Get yourself and all public methods inherited
    2. Public Method [] getDeclared Methods (); // Get all of its own methods (excluding inherited, unrelated to access rights)
    3. Public Method getMethod (String name, Class <>). ParameterTypes; // Represents calling the specified method
    Parameter: name: Represents the method name being invoked
    parameterTypes: Class type representing the parameters of the method being invoked
    4. Public Method getDeclared Method (String name, Class <>). ParameterTypes: // Represents calling a method in a specified class (excluding inheritance)
    Parameters:
    methodName: Represents the name of the method being called
    parameterTypes: Class types that represent the parameters of the called method, such as String.class

Using reflection invocation methods

  1. Find the bytecode where the called method is located
  2. Gets the called method object
  3. Call this method

There are methods in the Method class:
public Object invoke (Object ob, Object... Args: Represents the Method represented by the current Method
Parameters:
obj: Represents the underlying object to which the called method belongs
args: Represents the actual parameters passed when the method is called
Return:
Return results of underlying methods

* Call private methods (remember):
Private methods should be accessible before they are invoked
And because Method is a subclass of AccessibleObject, there is this method in Method.
sayGoodByeMethod.setAccessible(true);*

* Call static methods using reflection:
public Object invoke(Object obj,Object... args);
If the underlying method is static, the specified obj parameter can be ignored. Set the obj parameter to null. *

* Use reflection to invoke methods with variable parameters:
For parameters of reference type of array type, the underlying layer will automatically unpackage. To solve this problem, we use Object's one-dimensional array to wrap the actual parameters.*

(Keep in mind) In the future, invoke method is invoked by reflection. When passing actual parameters, whether basic data type or reference data type, or variable parameter type, it is no problem that all practical parameters are packaged in newObject []{}.

Code example:

1.Methodome.java

package methodome;

import java.lang.reflect.Method;

//Getting methods in User classes
public class Methodome {

    public static void main(String[] args) throws Exception{
        //getAllMethod();
        getOneMethod();
    }

    //Get a method
    public static void getOneMethod() throws Exception{
        //Get sayHello()
        Class clz=User.class;
        //Only through method signature can the only way be found.
        //Method signature = method name + parameter list (parameter type, number of parameters, parameter order)
        Method m=clz.getMethod("sayHello", null);
        System.out.println(m);
    }
    //Get all the methods
    public static void getAllMethod(){
        Class clz=User.class;
        Method[] mt=clz.getMethods();
        for(Method m:mt){
            System.out.println(m);
        }

        System.out.println("............................................................................................................................");
        mt=clz.getDeclaredMethods();
        for(Method m:mt){
            System.out.println(m);
        }
    }

}

class User{
    public void sayHello(){
        System.out.println("sayHello().......");
    }

    public void sayHi(String name){
        System.out.println("sayHi().........."+name);
    }

    private void sayGoodbye(String name,int age){
        System.out.println("sayGoodbye()......."+name+age);
    }
}

2.MethodInvokeDemo.java

package methodome;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;;
//Method invocation
public class MethodInvokeDemo {

    public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
        //Call sayHi (String name)
        Class clz=Emp.class;
        Method sayHiMethod=clz.getMethod("sayHi", String.class);
        Object obj=clz.newInstance();//obj represents the underlying object of the sayHi method
        Object res=sayHiMethod.invoke(obj, "wang");//wang represents the actual parameters of sayHi
        System.out.println(sayHiMethod);
        System.out.println(res);//res represents the return result of the sayHi method 

        //Call private sayGoodBye(String name,int age)
        Method sayGoodBye=clz.getDeclaredMethod("sayGoodBye", String.class,int.class);
        sayGoodBye.setAccessible(true);//Setting private methods accessible
        res=sayGoodBye.invoke(obj, "wang",23);

    }

}

class Emp{
    public void sayHello(){
        System.out.println("sayHello().......");
    }

    public int sayHi(String name){
        System.out.println("sayHi().........."+name);
        return 1;
    }

    private void sayGoodBye(String name,int age){
        System.out.println("sayGoodbye()......."+name+age);
    }
}

Posted by something on Sat, 25 May 2019 15:53:29 -0700