對於編程的實際任務,我們給出一個例子.class文件。我們需要打印出所有采用1 x int輸入和一些可打印輸出的方法,然後允許用戶通過命令行給出的一個輸入來運行該方法。但是,當我嘗試調用該方法時,會引發IllegalArgumentException。爲什麼在這裏由Method.Invoke引發IllegalArgumentException?
我的代碼拋出異常:
// 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.
}
由於一些故障安全檢查,我已經做了以下內容:
- 打印整數,以確認正確的掃描儀讀取它。
- 測試上的示例文件我知道的代碼:
public class TestFile
{
public int testMethod(int testInt)
{
return 2*testInt;
}
}
命令行輸出發生時:
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)
任何想法的原因,將不勝感激。我錯過了明顯的東西嗎? :)
編輯:下面是選擇方法的代碼:
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;
}
並在「methodInvoke」從主要的方法叫:
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);
和哪一行是86 – strash
Hey @ gen.Strash我已經評論過,在第一個代碼塊中,它是最後一行。 :) –
很明顯'inMethod'並不期待一個'Integer'(或'int')作爲它的第一個參數。既然你沒有告訴我們你如何獲得'inMethod',我們無法真正幫助你。如果它真的引用了一個接受單個'Integer'或'int'的方法,它就可以工作。 –