gpt4 book ai didi

java - 使用反射来调用采用不同参数的方法

转载 作者:行者123 更新时间:2023-11-29 03:32:03 25 4
gpt4 key购买 nike

我在一个类中有两个方法,一个采用 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;
}
}

第一个方法调用(即 isTooBig())在参数(String[])被包裹在 Object[] 中时起作用 .. 但是对于采用 String[] 和 int..

的下一个方法调用,这会失败

我该如何纠正这个问题?

最佳答案

  1. callMethod中,args已经是一个数组。你不需要包装它:

    result = this.methodTocall.invoke(null, args);
  2. main 中,警告(在 Eclipse 中)非常清楚:

    The argument of type String[] should explicitly be cast to Object[] for the invocation of the varargs method callMethod(Object...) from type MethodCalling. It could alternatively be cast to Object for a varargs invocation

    或者javac给出的警告

    warning: non-varargs call of varargs method with inexact argument type for last parameter;

    Boolean result1 = (Boolean) mc.callMethod(a);
    ^

    cast to Object for a varargs call

    cast to Object[] for a non-varargs call and to suppress this warning

    解决方法:

    Boolean result1 = (Boolean) mc.callMethod((Object) a);

关于java - 使用反射来调用采用不同参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17677420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com