これがコードです。
import java.lang.reflect.*;
class Invoke {
public static void main(String[] args) {
int ret;
if (args.length<2) {
System.out.println("Usage: Invoke <class> <method>");
return;
}
if (args.length == 2) {
ret = 2
} else {
System.out.println("Additional parameters not yet supported.");
return;
}
System.out.println("Results: " + ret);
}
}
問題は、プログラムを次のように実行しても...
java -cp Invoke;HelloJava4 Invoke HelloJava4 param1 param2 param3
...「param1 param2 param3」を 1 つの引数として認識します。注: 私のシステムのクラスパスは に設定されているC:\JavaSource
ため-cp Invoke;HelloJava4
、Invoke.class および HelloJava4.class の Invoke および HelloJava4 ディレクトリを検索します。
実行System.out.println(args.length);
すると、指定された正しい数の引数が出力されますが、次のif
ステートメントで確認すると、if
コード ブロックではなくコード ブロックが実行されelse
ます。
if (args.length == 2) {
ret = 2
} else {
System.out.println("Additional parameters not supported yet.");
return;
}
何を与える?:混乱している:
完全な未編集のコードは次のとおりです。
import java.lang.reflect.*;
class Invoke {
public static void main(String[] args) {
Object ret;
for (String arg : args)
System.out.println(arg);
System.out.println("Count: " + args.length + " \n");
if (args.length<2) {
System.out.println("Usage: Invoke <class> <method>");
return;
}
try {
Class theClass = Class.forName(args[0]);
Method theMethod = theClass.getMethod(args[1]);
if (args.length == 2) {
System.out.println("Invoking method " + args[1] + " within class " + args[0]);
ret = theMethod.invoke(null);
} else {
// pass parameters to .invoke() if more than two args are given
// for now, just exit...
System.out.println("Parameter passing not yet supported.");
return;
}
System.out.println("Invoked static method: " + args[1]
+ " of class: " + args[0]
+ " with no args\nResults: " + ret);
} catch (ClassNotFoundException e) {
System.out.println("Class (" + args[0] + ") not found.");
} catch (NoSuchMethodException e2) {
System.out.println("Class (" + args[0] + ") found, but method does not exist.");
} catch (IllegalAccessException e3) {
System.out.println("Class (" + args[0] + ") and method found, but method is not accessible.");
} catch (InvocationTargetException e4) {
System.out.println("Method threw exception: " + e4.getTargetException() );
}
}
}
そして、ここにそれが与える正確な出力があります:
C:\JavaSource>cd invoke
C:\JavaSource>javac invoke.java
Note: invoke.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
C:\JavaSource>cd ..
C:\JavaSource>java -cp Invoke;HelloJava4 Invoke HelloJava4 param1 param2 p
aram3
HelloJava4
param1
param2
param3
Count: 4
Class (HelloJava4) found, but method does not exist.