Anshul Khandelwal
Anshul Khandelwal

Reputation: 108

How do I get the class of an array via Class.forName(...)?

Let's say I have a method do expecting an array of arguments of some class E:

public class D {

    public void do(E ..arg){}

}

public static void main(String[] args) {
    Class z = Class.forName("D");
    Class e = Class.forName("E");
    Method m = z.getDeclaredMethod("do", e);
}

I want to get the method and the class using reflection, but this throws a

java.lang.NoSuchMethodException

Upvotes: 1

Views: 246

Answers (1)

cegredev
cegredev

Reputation: 1579

do expects an array of E.

So instead of passing getDeclaredMethod(...) e, pass it E[].class:

Method m = z.getDeclaredMethod("do", E[].class);

If you have to use Class.forName(...), you'll need to modify the name a bit. If you print out any object array's class, you'll see that it has a [L in the front and a ; at the end. Just add that to your argument and it should work:

Class<?> e = Class.forName("[L" + "E" + ";");
Method m = z.getDeclaredMethod("do", e);

You could also write a method that returns the class-name of an array with any amount of dimensions:

public static String getArrayClassName(int dimensions, String base) {
    return "[".repeat(dimensions) + "L" + base + ";";
}

Upvotes: 4

Related Questions