方法具有变量arglist时的Java反射

方法具有变量arglist时的Java反射,java,reflection,Java,Reflection,我得到了一些大致如下的信息: public class A { public void theMethod(Object arg1) { // do some stuff with a single argument } } public class B { public void reflectingMethod(Object arg) { Method method = A.class.getMethod("theMethod",

我得到了一些大致如下的信息:

public class A { 
    public void theMethod(Object arg1) {
        // do some stuff with a single argument
    }
}

public class B {
    public void reflectingMethod(Object arg) {
        Method method = A.class.getMethod("theMethod", Object.class);
        method.invoke(new A(), arg);
    }
}
我如何修改它,以便可以执行以下操作

public class A { 
    public void theMethod(Object... args) {
        // do some stuff with a list of arguments
    }
}

public class B {
    public void reflectingMethod(Object... args) {
        Method method = A.class.getMethod("theMethod", /* what goes here ? */);
        method.invoke(new A(), args);
    }
}

达特尼乌斯在对最初问题的评论中提出的建议奏效了,因为我已经开始思考如何去做了

public class A {
    public void theMethod(ArrayList<Object> args) { // do stuff 
    }
}

public class B {
    public void reflectingMethod(ArrayList<Object> args) {
        Method method;
        try {
            method = A.class.getMethod("theMethod", args.getClass());
            method.invoke(new A(), args);
        } catch (Exception e) {}
    }
}
公共A类{
public void方法(ArrayList args){//do stuff
}
}
公共B级{
public void reflectingMethod(ArrayList args){
方法;
试一试{
method=A.class.getMethod(“theMethod”,args.getClass());
调用(新的A(),args);
}捕获(例外e){}
}
}

您是否尝试过
列表
?效果不错。我以前尝试过,但在如何获取List的类时遇到了难题,因为泛型上不允许使用“.class”。创建一个新的空arraylist是可行的(只要方法签名使用arraylist作为参数。@Darthenius,一个列表并不是一个真正的varargs:-)顺便说一句,James,你应该可以通过执行List.class来查找这个方法(使用List)。我想…你要找的是被调用方。。。不是特定的调用方。对于反射,返回的方法是具有匹配方法名称和参数的方法。在本例中,方法名称为method,参数为对象数组。如果传递调用对象的不同子类类,它将不关心。Object[]。如果我在数组中传递了多个项,则在尝试调用反射的方法时,类会导致异常。例如,{“a”,“b”,“c”}的字符串[]抱怨有太多的参数(预期为1,但得到了三个)。一旦系统让m:Darthenius在原始问题的评论中的建议起作用,一旦我绞尽脑汁思考如何做,我就会将此移到一个答案。公共类A{public void theMethod(ArrayList args){//do stuff}}}public类B{public void reflectingMethod(ArrayList args){Method方法;try{Method=A.class.getMethod(“theMethod”,args.getClass());Method.invoke(new A(),args);}catch(异常e){}}@JamesMcMurray,实际上可以使用varargs。只需调用在对象[]内包装参数的方法,例如
方法。调用(new a(),new Object[]{new Object[]{“a”,“b”,“c”})
。基本上,invoke方法还接受varargs,因此可能会混淆数组的方向。
public class A {
    public void theMethod(ArrayList<Object> args) { // do stuff 
    }
}

public class B {
    public void reflectingMethod(ArrayList<Object> args) {
        Method method;
        try {
            method = A.class.getMethod("theMethod", args.getClass());
            method.invoke(new A(), args);
        } catch (Exception e) {}
    }
}