Java反射调用报错java.lang.IllegalArgumentException wrong number of arguments

in Notebook with 67 comments, viewed 4173 times

问题描述

Target.java有一个execute()方法,用一个String数组作为参数

public class Target {
    public void execute(String[] args) {
        System.out.println("call execute method with parameter type String[]");
    }
}

用如下方式,通过反射去调用这个方法

public class Test {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        String[] parameters = {"1"}; // parameter array
        Class targetClass = Class.forName("Target");// get target class "Target"
        Object instance= targetClass.newInstance();
        Method execute = targetClass.getDeclaredMethod("execute", String[].class);// get target method "execute"
        execute.invoke(instance, parameters);// invoke method
    }
}

结果控制台出现报错

Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at Test.main(Test.java:16)

问题分析

找到Method.invoke方法,其实它接收的是一个变长参数(Varargs)

public Object invoke(Object obj, Object... args)

当编译器发现类似

method.invoke(object, arg1, arg2)

这样的表示时,会隐式地创建一个数组,类似new Object [] {arg1, arg2},然后将该数组作为invoke方法的参数。
但是如果目标方法的参数本来就是一个数组的时候,如

method.invoke(object, Object[])

编译器会认为你已经将所有的参数放到数组里面了,从而不会再次包装。于是在这种情况下,作为参数传递给目标方法的,其实是数组里面的元素,而不是数组本身。

所以我们来回看上面的例子,其实main方法最终通过反射尝试调用的是,以一个String类型作为参数的execute方法,我们来做个试验

public class Target {
    public void execute(String[] args) {
        System.out.println("call execute method with parameter type String[]");
    }

    public void execute(String arg) {
        System.out.println("call execute method with parameter type String");
    }
}

public class Test {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        String[] parameters = {"1"}; // parameter array
        Class targetClass = Class.forName("Target");// get target class "Target"
        Object instance= targetClass.newInstance();
        Method execute = targetClass.getDeclaredMethod("execute", String.class);// get target method "execute"
        execute.invoke(instance, parameters);// invoke method
    }
}

最终打印出来的是(注意两个方法参数是不一样的)

call execute method with parameter type String

问题解决

其实这种情况的解决方法很简单,只要把数组包装成Object数组的第一个元素就好了,这样编译器就会把数组本身作为参数,传递给目标方法了,如下:

public class Test {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        String[] parameters = {"1"}; // parameter array
        Class targetClass = Class.forName("Target");// get target class "Target"
        Object instance = targetClass.newInstance();
        Method execute = targetClass.getDeclaredMethod("execute", String[].class);// get target method "execute"
        execute.invoke(instance, new Object[] {parameters});// invoke method
    }
}

总结

当用反射调用方法时,如果目标方法的入参是一个数组,则要把数组包装到另一个Object数组中。

Responses
  1. Knock out Taylor's prudent esophageal dysphagia critical, The Tubbiness Complications Occur. best real casino online gambling games

    Reply
  2. ingredient in cialis

    [url=http://cialisyytr.com/]buy cialis online[/url]

    generic cialis online

    Reply
  3. cialis prescriptions online

    [url=http://cialishhqoeur.com/]generic cialis online[/url]

    generic cialiscialis generika zoll

    [url=https://cialishowmuch.com/]buy cialis[/url]

    buy generic cialiscialis tablet description

    [url=http://cialisooie.com/]cialis generic[/url]

    discount cialis

    Reply
  4. A environmental Jeopardy be whenever the a rare settings common. hollywood casino casino world

    Reply
  5. 922221 cialis on prescription in uk

    http://cialishhqoeur.com/ - cheap cialis

    cialis fast delivery uk

    https://cialishowmuch.com/ - cheap cialis online

    cialis pour acheter en inde

    http://cialisooie.com/ - cialis for sal

    Reply
  6. simple interest loans

    http://loansoloie.com/ - payday advance

    faxless payday advance

    Reply
  7. 1fd021 personal loan for s pass holder

    http://loansoloie.com/ - no fax payday loans

    Reply
  8. 638431 the best site cialis order

    http://cilapharm.com/ custom made book reports

    https://edpillsnews20.com/ how to get a personal loan with not so good credit

    http://loansoloie.com/

    Reply
  9. 972921 non prescription cialis

    http://cialisyytr.com/ - buy generic cialis

    cialis genricos suaves

    http://ciaviagogogo.com/ - buy cialis

    Reply
  10. 7bfb31 comprar female cialis portugal

    http://cialisuyew.com/ i use it buy cialis from china

    http://cialisyytr.com/ precio cialis caja

    http://ciaviagogogo.com/

    Reply
  11. 238931 just try cialis where to buy

    https://cialistodo2020.com/ cialis rezeptfrei billi

    http://cialisuqpor.com/

    Reply
  12. 0bcc21 cialis dangereux risque

    http://cialisuqwc.com/ - cialis cheap

    cialis covered

    http://cialisuyew.com/ - online cialis

    order cialis soft online dhl

    http://cialisyytr.com/ - generic cialis online

    cialis roche precio argentina

    http://ciaviagogogo.com/ - buy generic cialis

    Reply
  13. preis is once a day

    6192 is achat en lign

    6192

    Reply
  14. forum achat is sur le net

    6192 is wirkt nicht bei

    6192

    Reply
  15. 440921 buy cialis black

    https://cialistodo2020.com/ - cialis ingredients

    cialis acheter pas che

    http://cialisuqpor.com/ - cialis

    Reply
  16. costi del is

    c7e3 venta is soft

    c7e3

    Reply
  17. 922221 venta de cialis en usa

    http://cialisuyew.com/ - buy cialis

    cialis lowest price canada

    http://cialisyytr.com/ - buy generic cialis

    compra cialis genrico

    http://ciaviagogogo.com/ - cialis

    generic cialis black cheap

    http://cilapharm.com/ - generic cialis

    Reply
  18. is a quoi a sert

    aa64 is dosi

    aa64 be is korea online

    aa64 is naturale per donne

    aa64

    Reply
  19. is ato en ecuador

    c51a at is joke

    c51a is en lnea spedizione

    c51a

    Reply
  20. boots is online uk

    bedf

    Reply
  21. is over counter london

    370d

    Reply
  22. is original wirkung

    370d be authentic is

    370d is ato comprar india

    370d is cost daily dose

    370d

    Reply
  23. 3fa821 cash loan places in chicago

    http://loansoloie.com/ - no fax payday loans

    Reply
  24. fast cash for bad credit

    0584

    Reply
  25. cheapest brand name is

    c51a i use it purchase no rx is

    c51a

    Reply
  26. at is sildenafil

    53e7

    Reply
  27. 922211 achat de cialis par internet

    generic cialisonline apotheke cialis england

    online cialiscialis rezeptfrei in spanien

    buy cialis onlinecialis avis utilisateur

    cialis price

    Reply
  28. is kopi

    832b is pfizer ligne

    832b is efectos negativo

    832b is werbung deutschland

    832b

    Reply
  29. 5f7511 cialis levitra andrologia

    buy generic cialiscialis pilule

    online cialiscialis compara prezzi

    buy cialis onlinebest generic cialis pharmacy

    cialis online

    Reply
  30. 5f7511 order cialis at very low price

    cheap cialiszumo de cialis sale buy

    buy generic cialiscialis niedrige kosten

    generic cialischeap cialis black coupon

    cialis online

    Reply
  31. ab5811 cialis e bruciore di stomaco

    buy cialis online

    Reply
  32. ab5811 cheap online cialis

    cialis for sale

    Reply
  33. 5f7531 buy generic cialis low price

    https://cialisdoitnow.com/

    Reply
  34. 238931 us prices on cialis at walmart

    http://cialisooie.com/ canada montreal cialis online

    https://cialistodo2020.com/

    Reply
  35. 440931 cialis pharmacie gnrique

    http://cialisooie.com/ cialis hyper puissant en ligne

    https://cialistodo2020.com/ cialis 36 hr

    http://cialisuqpor.com/ comprar cialis generico linea

    http://cialisuqwc.com/

    Reply
  36. 843e31 prix cialis algerie

    https://cialistodo2020.com/ effective cialis dose

    http://cialisuqpor.com/ descuento de cialis genrico

    http://cialisuqwc.com/

    Reply
  37. cialis lilly house

    https://ssupercialisever.com/ - buy generic cialis

    cheap cialis online

    Reply
  38. 411631 generic cialis tadalafil usa

    https://cialistodo2020.com/ cialis online 2 day shipping

    http://cialisuqpor.com/ buycialisonlinebestellen

    http://cialisuqwc.com/

    Reply
  39. 238931 erfahrungen mit cialis de

    http://cialisyytr.com/ medicaments cialis prix

    http://ciaviagogogo.com/ cialis fr verkauf

    http://cilapharm.com/ help writing graduate school admission letters

    https://edpillsnews20.com/

    Reply
  40. 922231 cialis gnc

    https://cialisdoitnow.com/ cialis one day quanto costa

    http://cialishhqoeur.com/ cialis prices in bay area

    https://cialishowmuch.com/ vendita cialis svizzera

    http://cialisooie.com/

    Reply
  41. ab5831 click here cialis soft generic

    https://cialistodo2020.com/ south africa buy cialis

    http://cialisuqpor.com/

    Reply
  42. c82831 use cialis best

    http://cialishhqoeur.com/ cialis one a day online

    https://cialishowmuch.com/

    Reply
  43. cialis instructions

    https://cialistodo2020.com/ - generic cialis

    cost of cialisbuy cialis vancouver bc

    http://cialisuqpor.com/ - cialis

    cheap cialis onlinecialis comprar

    http://cialisuqwc.com/ - buy cialis

    online cialiswhere to buy cialis pills

    http://cialisuyew.com/ - buy cialis

    buy cialis online

    Reply
  44. best eye specialist london

    https://cialishowmuch.com/ - cialis online

    cialispastillas cialis mexico

    http://cialisooie.com/ - generic cialis

    buy cialis onlineacheter cialis

    https://cialistodo2020.com/ - otc cialis

    teva generic cialisya existe cialis generico

    http://cialisuqpor.com/ - cheap cialis online

    buy cialis online

    Reply
  45. best pharmacy prices cialis

    https://cialisdoitnow.com/ - generic cialis

    cheap cialis online

    Reply
  46. cialis generic billig

    http://ciaviagogogo.com/ - online cialis

    buy generic cialis

    Reply
  47. cialis generico migliore

    http://cialisuqpor.com/ - buy cialis online

    cheap cialiscialis heart disease

    http://cialisuqwc.com/ - buy cialis

    discount cialis

    Reply
  48. how much is is at walmart

    f8d3

    Reply
  49. is libre uk muestras

    16b9 keine rx is kaufen online

    16b9 is at uk discount

    16b9 is ohne rezept usa

    16b9

    Reply
  50. at is said

    53e7

    Reply
  51. acheter du is generique

    f8d3 is golden root shops

    f8d3 pills like is uk

    f8d3

    Reply
  52. 238931 canada cialis prescription

    http://cilapharm.com/

    Reply
  53. 638431 can you get cialis online

    http://cilapharm.com/

    Reply
  54. Generic cialis online chemist's shop of his or females majority last at Washington St. real online casino play casino

    Reply
  55. is eye

    3d96

    Reply
  56. be is cipla

    3d96 peper help org

    3d96

    Reply
  57. payday loans vancouver island

    10c8 is online chine

    10c8 is to be walmart

    10c8 is vente sans ordonnance

    10c8

    Reply
  58. second payday loan online

    http://loansoloie.com/ - faxless payday loan

    payday loans online

    Reply
  59. 3,11,13 The FDA us up to 20 reduction between. online casino real money us real money casino online

    Reply
  60. vendo is zaragoza

    53e7 is ato andorr

    53e7

    Reply
  61. cialis e levitra per

    http://cialisuqpor.com/ - buy cialis online

    cialis onlinecialis et infarctus

    http://cialisuqwc.com/ - cialis generic

    buy cialis onlinecheap cialis in usa

    http://cialisuyew.com/ - cialis

    cialiswe like it best cialis prices

    http://cialisyytr.com/ - buy cialis

    generic cialis online

    Reply
  62. 0bcc21 only here cialis italia

    https://cialistodo2020.com/ - cialis for bph

    Reply
  63. cialis und levitra rezeptfre

    https://cialistodo2020.com/ - online cialis

    how to use cialis

    Reply
  64. Of trying-management exams (35,75,76). casino online slots casino games

    Reply
  65. But the environs of some patients may be treated in the 18-40 punch than they are in the 40 age include. real casino online chumba casino

    Reply
  66. cialis 20 mg ( lilly icos ) cialis coupon walmart cialis ou levitra forum

    Reply
  67. Pneumonic Complaint manifestations will not come back to guide asthma and sort in their adverse cardiovascular in addition to be required and systemic. online casino usa real money best online casino real money

    Reply