我在一个类中有两个方法,一个接受一个Comparable[]
作为参数并返回一个Boolean
值。另一个方法接受一个Comparable[]
和一个int
值,返回一个Boolean
。我尝试编写一些方法来使用反射调用这些方法。
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MethodCalling {
private static Class classTocall;
private static Method methodTocall;
public MethodCalling(String classname){
super();
try {
this.classTocall = Class.forName(classname);
} catch (ClassNotFoundException e) {
System.out.println("failed to get class!!");
e.printStackTrace();
}
}
public void setMethod(String method,Class...args){
try {
this.methodTocall = this.classTocall.getMethod(method, args);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
public Object callMethod(Object...args){
Object result = null;
try {
if(this.methodTocall != null){
result = this.methodTocall.invoke(null, new Object[]{args});
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
String[] a = new String[]{"H","E","L","L","O"};
MethodCalling mc = new MethodCalling("SizeChecker");
mc.setMethod("isTooBig", Comparable[].class);
Boolean result1 = (Boolean) mc.callMethod(a);
System.out.println("too big="+result1);
mc.setMethod("isCorrectLength",Comparable[].class,int.class);
Boolean result2 = (Boolean) mc.callMethod(a,5);
System.out.println("length is 5="+result2);
}
}
class SizeChecker{
public static boolean isTooBig(Comparable[] a){
return a.length > 10;
}
public static boolean isCorrectLength(Comparable[] a,int x){
return a.length == x;
}
}
当参数(即 a )被包裹在一个. 中时,第一个方法调用(即isTooBig()
)起作用。但是对于采用 a和一个 int的下一个方法调用,这将失败。String[]
Object[]
String[]
我该如何纠正?