For a programming practical task, we are given an example .class file. We need to print out all methods that take 1 x int input and some printable output, and then allow the user to run that method with one input as given through the command line. However, when I try to invoke the method, an IllegalArgumentException is thrown.
My code that throws the exception:
// Request the user enter an integer and run the requested method.
private static void methodInvoke(Method inMethod, Scanner scanner) throws
NumberFormatException,IllegalAccessException,InvocationTargetException,InstantiationException,ClassNotFoundException
{
Integer userNumber = new Integer(0);
Class methodClass = Class.forName(inMethod.getDeclaringClass().getName());
Object methodObject = methodClass.newInstance();
// Debug to confirm only default constructors.
Constructor constructList[] = methodClass.getConstructors();
for(Constructor c : constructList)
{ System.out.println(c.toString()); }
System.out.println("Enter a number to supply to: '" + inMethod.getName()
+ "(int)':");
userNumber = Integer.getInteger(scanner.nextLine());
// Throws IllegalArgumentException here:
System.out.println(inMethod.invoke(methodObject, userNumber));
}
As some fail-safe checks I've done the following:
- Printed list of constructors to confirm no arguments are required.
- Printed the integer to confirm scanner reads it correctly.
-
Tested on an example file for which I know the code:
public class TestFile { public int testMethod(int testInt) { return 2*testInt; } }
Command line output when it occurs:
Enter the name of the class to analyse, excluding '.class':
TestFile
(0): testMethod
Select a method with the method index from above: '(0) to (n-1)':
0
public TestFile() <--- Where I print out the constructors.
Enter a number to supply to: 'testMethod(int)':
1
Error: Invalid argument. <--- Where I catch the exception and print an error message.
java.lang.IllegalArgumentException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at MethodMetrics.methodInvoke(MethodMetrics.java:86)
at MethodMetrics.main(MethodMetrics.java:30)
Any ideas as to the cause would be appreciated. Am I missing something obvious? :)
I understand similar questions have been asked before, but seemingly cannot nail down the issue in my situation, the others tend to be due to varargs issues.
Aucun commentaire:
Enregistrer un commentaire