What is wrong with my Method.invoke call?

守給你的承諾、 提交于 2019-12-04 23:32:28

Use

public static void main(String[] args) throws Throwable {
    if (args.length == 0)
        Main.class.getMethod("main", String[].class)
                  .invoke(null, new Object[] {new String[] { "test" }});
}

The problem is that invoke has vararg parameter which could be either array or plain list of objects and Java arrays are covariant. So .invoke(null, new String[] { "test" }) is interpreted by compiler in the same way as .invoke(null, new Object[] { "test" }). You should have compiler warning about this ambiguity.

Cast new String[] { "test" } in a new Object[] {}.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!