Java:非法参数异常

时间:2009-12-27 00:55:10

标签: java unit-testing reflection illegalargumentexception

我得到IllegalArgumentException,但我无法弄明白为什么。

我正在尝试访问的功能:

private static Player checkEvents(Player[] players, GameMaster bananas)

有问题的代码:

@Test
public void testCheckEvents() throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    Game g = new Game();
    GameMaster gm = new GameMaster(4);
    Player[] p = new Player[] {new Player(gm), new Player(gm), new Player(gm), new Player(gm)};

    Method checkEvents = g.getClass().getDeclaredMethod("checkEvents", new Class[] {p.getClass(), GameMaster.class});
    checkEvents.setAccessible(true);

    checkEvents.invoke(p, gm); // fails here
}

失败:

testCheckEvents(nth.bananas.GameTest)
java.lang.IllegalArgumentException: wrong number of arguments

我做错了什么?

1 个答案:

答案 0 :(得分:4)

invoke的第一个参数必须是要调用该方法的对象:

checkEvents.invoke(g, p, gm)

由于您的方法为static,您还可以使用null代替对象引用g