java.lang.IllegalArgumentException:字符串数组上的参数类型不匹配 [英] java.lang.IllegalArgumentException: argument type mismatch on string array

查看:586
本文介绍了java.lang.IllegalArgumentException:字符串数组上的参数类型不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我动态调用方法的代码:

This is my code to invoke a method dynamically:

String[] parameters = new String[requiredParameters.length];
//here i put some values in the parameters array
method = TestRecommendations.class.getMethod("level1ClassSimilarityForUser",
                                    String[].class);
System.out.println(":" + parameters[0] + ":");
results = (ResultSet) method.invoke(new TestRecommendations(), parameters)

参数是一个字符串数组,这是我的 level1ClassSimilarityForUser 方法的声明

parameters is a string array, and this is the declaration of my level1ClassSimilarityForUser method

public ResultSet level1ClassSimilarityForUser(String[] userURI) {

我收到此错误:

java.lang.IllegalArgumentException: argument type mismatch

    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:497)


推荐答案

调用期望 Object [] 作为第二个参数(varargs只是一个便利语法)。
我认为在你的情况下, String [] 不作为第一个vararg参数,而是完整的vararg Object [] 因此您的单个字符串用作与 String [] 不匹配的参数。

在您的情况下,显式包装您的参数在对象数组中,在将它提供给 invoke 之前应该有效。

所以 results =(ResultSet)method.invoke(new TestRecommendations(),new Ojbect [] {parameters})而不是

invoke expects an Object[] as second argument (varargs is just a convenience syntax). I think in your case the String[] is not taken as the first vararg argument, but the complete vararg Object[] and thus your single strings are used as arguments which does not match String[].
In your case, explicitly wrapping your parameters in an Object array before giving it to invoke should work.
So do results = (ResultSet) method.invoke(new TestRecommendations(), new Ojbect[] { parameters }) instead

这篇关于java.lang.IllegalArgumentException:字符串数组上的参数类型不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆