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

时间:2013-07-16 13:08:45

标签: java reflection

我在一个类中有两个方法,一个接受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 ..

我该如何纠正?

4 个答案:

答案 0 :(得分:2)

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

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

      

    类型String[]的参数应显式转换为Object[],以便从类型callMethod(Object...)调用varargs方法MethodCalling。也可以将其转换为Object以进行varargs调用

    javac

    给出的警告
      

    警告:非varargs调用varargs方法,最后一个参数的参数类型不精确;

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

    转换为Object进行varargs调用

         

    转换为Object[]进行非varargs调用并禁止此警告

    解决方案:

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

答案 1 :(得分:1)

这里的问题在于

result = this.methodTocall.invoke(null, new Object[]{args});

当你向方法传递参数时,你将它们包装在另一个Object []中,这是一个不必要的,当args包含多个参数时(比如第二个方法调用中的字符串和int),将这些参数隐藏在Object数组中,使它们显示为一个参数。这就是你得到错误的原因。

使用以下更改解决此问题:

result = this.methodTocall.invoke(null, args);

然后将您的主要方法更改为:

String[] a = new String[]{"H","E","L","L","O"};
MethodCalling mc = new MethodCalling("wat.SizeChecker");
mc.setMethod("isTooBig", Comparable[].class);
/* change here: place the single parameter into a parameter array */
Boolean result1 = (Boolean) mc.callMethod(new Object[]{a});
System.out.println("too big="+result1);

mc.setMethod("isCorrectLength",Comparable[].class, int.class);
/* since the callMethod accepts varargs, these are automatically placed in an Object[] */
Boolean result2 = (Boolean) mc.callMethod(a, 5);
System.out.println("length is 5="+result2);

答案 2 :(得分:1)

简单的好朋友,问题(2)

1。您将String数组作为Object数组传递给callMethod()函数,而您需要将String数组作为一个参数传递,但它将作为5个参数传递,简单只需替换此代码

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

到这个

Boolean result1 = (Boolean) mc.callMethod(new Object[]{args});

这可以确保整个数组作为一个参数传递。

2。另一个问题是,你再次用一个参数调用方法(这个this.methodTocall.invoke(null, new Object[]{args})),实际上在第二次调用时你将所有参数作为一个参数与Object[]{args}一起调用并调用该方法。 所以改变这一行

result = this.methodTocall.invoke(null, new Object[]{args});

用这个

result = this.methodTocall.invoke(null, args);

答案 3 :(得分:0)

您需要将String数组声明为对象:

Object a = new String[] { "H", "E", "L", "L", "O" };

直接使用args方法的invoke参数:

result = this.methodTocall.invoke(null, args);
相关问题