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

4
  • What is the error? Commented Dec 17, 2018 at 16:23
  • This should work. Give exception details, for example you method may be private Commented Dec 17, 2018 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? Commented Dec 17, 2018 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. Commented Dec 17, 2018 at 18:22

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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?
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);

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.