Java reflection: getMethod(String method, Object[].class) not working

前端 未结 3 1920
囚心锁ツ
囚心锁ツ 2021-01-02 02:58

I have the following code:

public void myMethod(Object... args) {
    System.out.println(\"this is myMethod\");
}

public void invokeMyMethod() {
    Method          


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-02 03:06

    The problem here is with the variable arguments (the Object...) that Method.invoke takes.

    Changing this line

     s.invoke(this, ex);
    

    to this

     s.invoke(this, (Object)ex);
    

    will work.

    In the background, Object... is passed as an Object[]. Java's seeing your Object[] and choosing not to wrap it up in another Object[]. By casting to Object, it now just sees that and reverts to its normal wrap-it-up behaviour - the same as what other answers are doing manually.

提交回复
热议问题