Java:非法参数异常

问题描述:

我得到IllegalArgumentException,但我找不出原因。Java:非法参数异常

我试图访问的功能:

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 

我在做什么错?

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

checkEvents.invoke(g, p, gm) 

因为你的方法是static,你也可以用null代替对象引用g

+3

要扩展@ hjhill的正确答案,如果Method对象引用静态方法,则会忽略invoke()的第一个参数。 – 2009-12-27 01:17:29