How to get this Method object via reflection?

删除回忆录丶 提交于 2020-01-06 05:48:07

问题


This is the class:

public class Foo {
  public void bar(Integer[] b) {
  }
}

Now I'm trying to get this method via reflection:

Class cls = Foo.class;
Class[] types = { /* what is here */ };
cls.getMethod("bar", types);

How to create this "type"?


回答1:


Integer[].class - this is the class literal for the integer array. If you need it dynamically, you can use Class.forName("[Ljava.lang.Integer;") as David noted.

If you don't know the exact types, you can call getMethods(), iterate the returned array and compare names.

Spring has an utility class ReflectionUtils, which have findMethod(..) that do this.




回答2:


Integer[].class

blah blah blah blah blah blah




回答3:


It is a bit stupid that Class has no method to give the corresponding array class, only the other way around. Here is a workaround:

<E> public static Class<E[]> arrayClass(Class<E> elementClass) {
    @SuppressWarnings("unchecked")
    Class<E[]> arrayClass = (Class<E[]>) Array.newInstance(elementClass, 0).getClass();
    return arrayClass;
}

With this method you could write

Class cls = Foo.class;
Class[] types = { arrayClass(Integer.class) };
cls.getMethod("bar", types);

Of course, if you can write Integer.class, you could also write Integer[].class. So this is only useful if you know your method takes an array of some class which you only get as a class object, otherwise use the answers given by Bozho.



来源:https://stackoverflow.com/questions/5070519/how-to-get-this-method-object-via-reflection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!