如何使用反射在java中调用方法 [英] How to invoke a method in java using reflection

查看:142
本文介绍了如何使用反射在java中调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用反射调用带参数的方法?

How can I invoke a method with parameters using reflection ?

我想指定这些参数的值。

I want to specify the values of those parameters.

推荐答案

这是一个使用包含原语的反射来调用方法的简单示例。

Here's a simple example of invoking a method using reflection involving primitives.

import java.lang.reflect.*;

public class ReflectionExample {
    public int test(int i) {
        return i + 1;
    }
    public static void main(String args[]) throws Exception {
        Method testMethod = ReflectionExample.class.getMethod("test", int.class);
        int result = (Integer) testMethod.invoke(new ReflectionExample(), 100);
        System.out.println(result); // 101
    }
}

要坚强,你应该抓住并且处理所有已检查的与反射相关的异常 NoSuchMethodException IllegalAccessException InvocationTargetException

To be robust, you should catch and handle all checked reflection-related exceptions NoSuchMethodException, IllegalAccessException, InvocationTargetException.

这篇关于如何使用反射在java中调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆