这是代码。
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”识别为一个参数。注意:我的系统的类路径设置为C:\JavaSource
,所以-cp Invoke;HelloJava4
让它在 Invoke 和 HelloJava4 目录中搜索 Invoke.class 和 HelloJava4.class
如果我这样做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.