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, Class methodClass, Scanner scanner) throws
NumberFormatException,IllegalAccessException,InvocationTargetException,InstantiationException,ClassNotFoundException
{
Integer userNumber = 0;
Object methodObject = methodClass.newInstance();
System.out.println(inMethod.toString()); // Test to confirm printing the correct method.
System.out.println("Enter a number to supply to: '" + inMethod.toString() + ":");
userNumber = Integer.getInteger(scanner.nextLine());
System.out.println(inMethod.invoke(methodObject, userNumber)); // Throws IllegalArgumentException here.
}
As some fail-safe checks I've done the following:
- 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 a number to supply to: 'public int TestFile.testMethod(int):
1
Error: Invalid argument.
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:79)
at MethodMetrics.main(MethodMetrics.java:29)
Any ideas as to the cause would be appreciated. Am I missing something obvious? :)
EDIT: Here's the code that selects the methods:
private static Method[] getIntMethods(Class classToTest) throws NullPointerException
{
int counter = 0;
Method[] allFoundMethods = classToTest.getDeclaredMethods(); // Unnecessary to check for SecurityException here
Method[] returnMethods = new Method[allFoundMethods.length];
if(returnMethods.length > 0) // Only bother if the class has methods.
{
for(Method mTest : allFoundMethods)
{
if(mTest.getParameterTypes().length == 1)
{
if(mTest.getParameterTypes()[0].getName().equals("int"))
{
returnMethods[counter++] = mTest;
}
}
}
returnMethods = Arrays.copyOf(returnMethods, counter);
}
return returnMethods;
}
AND where "methodInvoke" is called from the main method:
System.out.println("Select a method with the method index from above: '(0) to (n-1)':");
selectedMethod = scanner.nextLine();
methodInvoke(foundMethods[Integer.parseInt(selectedMethod)], scanner);