关于Method.invoke总结

package com.KnowledgeTest;

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

public class InvokeTest {
    public void Show() {
        System.out.println("The method has no arguments.");
    }

    //如果参数声明用的是int和double的话,将会报如下错误:
    //Exception in thread "main" java.lang.NoSuchMethodException:
    //com.KnowledgeTest.InvokeTest.Show(java.lang.String, java.lang.Integer, java.lang.Double)
    
    public void Show(String name, Integer age, Double time) {
        System.out.println("Student name is: " + name);
        System.out.println("Student age is: " + age);
        System.out.println("Student time is: " + time);
    }

    public static void message() {
        System.out.println("The method is static.");
    }

    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        InvokeTest invokeTest = new InvokeTest();

        //调用有参方法
        
        Object[] objects = new Object[]{"Tom", 22, 13.4};	//声明参数数组
        Class[] classes = new Class[objects.length];	//创建一个Class数组
        for(int i = 0; i < objects.length; i++) {
            classes[i] = objects[i].getClass();		//将参数的Class装到Class数组中,这几步是用来判断调用哪一个方法(重载方法)
        }
        Method method = invokeTest.getClass().getMethod("Show", classes);
        method.invoke(invokeTest, objects);

        System.out.println();

        //调用无参方法
        
        Method method1 = invokeTest.getClass().getMethod("Show");
        method1.invoke(invokeTest);

        System.out.println();

        //调用静态方法
        
        Method method2 = invokeTest.getClass().getMethod("message");
        method2.invoke(null);
      }
}

你可能感兴趣的:(关于Method.invoke总结)