参数类型不匹配:简单情况下的 IllegalArgumentException

Argument type mismatch: IllegalArgumentException on simple case

我有一个关于 IllegalArgumentException 的著名问题,我不知道为什么。这是我的 class:

  public class DataMapper   {
          ... An lot of others methods that does not have the same name (because I created a method specifically for checking this exception

          private void hello(String ahem)   {
              logger.info("Hey !");
          }
}

在我的测试用例中(我尝试调用我的方法):

 @Test
    public void test()  {
       Class<?> targetClass = DataMapper.class;

       try    {
           Object t = targetClass.newInstance();

           Class<?>[] cArg = new Class[1];
           cArg[0] = String.class;

           Method method = targetClass.getDeclaredMethod("hello", cArg);
           method.setAccessible(true);
           method.invoke(t, cArg);
      }   catch(NoSuchMethodException e)   {
            logger.error("Name does not exist : ", e);
            Assert.fail();
        } catch (Exception e) {
            logger.error("It is broken : ", e);
            Assert.fail();
        }
   }

它总是落在 IllegalArgumentException 上。 Method 对象听起来符合我的期望,tho:

知道那里发生了什么吗? 在任何重复标志之前,我已经检查过那些,没有什么是完全相同的,也没有用:

This one 构造了一个方法列表,事实上他有 2 个或更多同名方法,但参数不同。 是错误的,因为他将 String[] 作为参数传递,而编译器错误地解释了完整参数列表的对象。 The third one是因为他忘了传一个参数。

在这一行中:

method.invoke(t, cArg);

您必须传递 String 而不是 cArg,后者是 Class 的数组。像下面这样的东西会起作用:

method.invoke(t, "Test");