简体   繁体   中英

Argument type mismatch: IllegalArgumentException on simple case

I have this famous problem about IllegalArgumentException, and I cannot figure out why. Here is my 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 !");
          }
}

In my test case (where I try to invoke my method):

 @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();
        }
   }

It always falls on an IllegalArgumentException. The Method object sounds to agree with my expectations, tho:

方法的论点

我的论点数组

Any ideas what is happening there ? Before any duplication flags, I already checked those, and nothing is exactly the same, nor works:

This one constructs a list of methods, fact was he had 2 or more methods with the same name, but not the same arguments. The second one was in mistake because he was passing a String[] as the arguments, and the compiler was misinterpreting the object for the full arguments list. The third one was because he forgot to pass an argument.

In this line:

method.invoke(t, cArg);

You must pass a String as instead of cArg which is an array of Class . Something like the following will work:

method.invoke(t, "Test");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM