如何使用varargs和反射 [英] How to work with varargs and reflection

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

问题描述

简单的问题,该代码是如何工作的?

Simple question, how make this code working ?

public class T {

    public static void main(String[] args) throws Exception {
        new T().m();
    }

    public // as mentioned by Bozho
    void foo(String... s) {
        System.err.println(s[0]);
    }

    void m() throws Exception {
        String[] a = new String[]{"hello", "kitty"};
        System.err.println(a.getClass());
        Method m = getClass().getMethod("foo", a.getClass());
        m.invoke(this, (Object[]) a);
    }
}

输出:

class [Ljava.lang.String;
Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)


推荐答案

Test.class.getDeclaredMethod("foo", String[].class);

有效。问题是 getMethod(..)只搜索 public 方法。来自javadoc:

works. The problem is that getMethod(..) only searches the public methods. From the javadoc:


返回一个Method对象,该对象反映此Class对象所表示的类或接口的指定公共成员方法。

Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.

更新:成功获取方法后,您可以使用以下方法调用它:

Update: After successfully getting the method, you can invoke it using:

m.invoke(this, new Object[] {new String[] {"a", "s", "d"}});

即 - 创建一个新的对象数组使用一个元素 - String 数组。使用您的变量名称,它将如下所示:

that is - create a new Object array with one element - the String array. With your variable names it would look like:

m.invoke(this, new Object[] {a});

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

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