0

How to define 2-dim array in reflection?

int[][] x={ {1,1,2},{1,1,2},{3,3,3}};
Class<?> c= Class.forName("Ex2");
Class nameClassArr = Class.forName("[[I");
Method methodcall1= c.getDeclaredMethod("biggestRect", nameClassArr );
Object invoke = methodcall1.invoke(c, x);

In this way I get warning in compilation:

javac testEx2.java
testEx2.java:113: warning: non-varargs call of varargs method with inexact argument type for last parameter;
                Object invoke = methodcall1.invoke(c, x);
                                                      ^
  cast to Object for a varargs call
  cast to Object[] for a non-varargs call and to suppress this warning
1 warning

And error in running:

java testEx2
Exception in thread "main" java.lang.NoSuchMethodException: Ex2.biggestRect([[I)
        at java.lang.Class.getDeclaredMethod(Unknown Source)
        at testEx2.main(testEx2.java:112)

In class Ex2 I have a function "biggestRect" that her arguments is 2-dim array

ShiraOzeri
  • 291
  • 4
  • 14
  • What is the error? – GBlodgett Dec 17 '18 at 16:23
  • This should work. Give exception details, for example you method may be private – jaudo Dec 17 '18 at 16:27
  • 1
    I have to ask: why do you want to do this? Reflection can do a lot of things and get at the root of a lot of places, but given that arrays themselves are a special kind of object, I never saw much value in reflecting on them since it was easier to just invoke the array I wanted. Could you explain your motivation here? – Makoto Dec 17 '18 at 16:46
  • GBlodgett , jaudo I Edit my questions and add the warning and the error. thanks. @Makoto I have to check assignments for students. To the assignments have the same class name(Ex2.java),I do a code that compile and run the assignments.but sometimes the function dont exist so the test fail when i call to function. – ShiraOzeri Dec 17 '18 at 18:22

1 Answers1

0

Instead of getting the name of the class for int[][] with the string just pass the class object there

Method methodcall1= c.getDeclaredMethod("biggestRect", int[][].class );

Also see here Why do I get "object is not an instance of declaring class" when invoking a method using reflection?, the first parameter of the call

methodcall1.invoke(c, x);

should be the object instance, not the class object

Nadir
  • 1,369
  • 1
  • 15
  • 28
  • I would be happy if you will see the error,I Edit my question and add the error.  I get another error from this question. And what value can I add to invoke? – ShiraOzeri Dec 17 '18 at 18:26
  • Like I said, remove the Class.forName("[[I"), and use the int[][].class directly. Then instead of methodcall1.invoke(c, x); where c is a Class object do methodcall1.invoke(new Ex2(), x); – Nadir Dec 18 '18 at 06:31