0

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"?

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
yegor256
  • 102,010
  • 123
  • 446
  • 597

3 Answers3

3

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.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • can I get this `Integer[].class` without an explicit static call? Imagine that I have `className = "Integer[]"`.. – yegor256 Feb 21 '11 at 20:59
  • 2
    @yegor256 - This should do the trick, from [Java Reflection: Arrays](http://tutorials.jenkov.com/java-reflection/arrays.html#class): `"[Ljava.lang.Integer;"` – David Harkness Feb 21 '11 at 21:42
  • @yegor256 @David Harkness is correct, adding it to the answer. – Bozho Feb 21 '11 at 21:45
1
Integer[].class

blah blah blah blah blah blah

irreputable
  • 44,725
  • 9
  • 65
  • 93
0

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.

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210