关于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);
      }
}

转载于:https://my.oschina.net/are1OfBlog/blog/181852

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值