1

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

9
  • do is not a static method, I tried z.getMethod("do",e); didn't work Commented May 25, 2020 at 19:15
  • I also tried z.getMethod("do",Object[].class); That also didn't work; Commented May 25, 2020 at 19:17
  • 1
    You are trying to to get a reference to a method with the name do and a single parameter of type E. But the method has a E[] parameter... Commented May 25, 2020 at 19:24
  • 1
    Does that code compile at all? I might be a bit rusty in java but I'm not 100% sure you can call a method do and varargs with .. instead of ... Commented May 25, 2020 at 19:25
  • 1
    You can't do it with e, because that's not what the method expects. Commented May 25, 2020 at 19:26

1 Answer 1

4

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 + ";";
}
Sign up to request clarification or add additional context in comments.

4 Comments

Is there any way, I can get "e" as an array of "E" using reflection? I have a requirement to do with Class e = Class.forName("E");
Actually I have the String "E" and using this I want to getMethod.
@AnshulKhandelwal There is, give me a sec.
See also Class::arrayType since Java 12.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.