method的invoke方法声明如下:
{code}
public Object invoke(Object obj, Object... args)
{code}
如果实际调用的方法参数是数组怎么办?比如下面这段代码会报错:
{code}
public class MBlogServiceImpl {
public List<Blog> queryBlogByIds(Long[] id) {
System.out.println("exe");
return new ArrayList<Blog>();
}
}
MBlogServiceImpl serviceBean = new MBlogServiceImpl();
Long[] params = new Long[]{1l};
Long param = new Long(1);
Method method = serviceBean.getClass().getMethod("queryBlogByIds",params.getClass());
Object obj = method.invoke(serviceBean,params);
System.out.println(obj);
{code}
其实method.invoke这行代码,eclipse编译的时候也会出现黄色警告:
The argument of type Long[] should explicitly be cast to Object[] for the invocation of the varargs method invoke(Object, Object...) from type Method. It could alternatively be cast to Object for a varargs invocation
把数据放在new Object[]{}就好了。
Object obj = method.invoke(serviceBean,new Object[]{params});
{code}
public Object invoke(Object obj, Object... args)
{code}
如果实际调用的方法参数是数组怎么办?比如下面这段代码会报错:
{code}
public class MBlogServiceImpl {
public List<Blog> queryBlogByIds(Long[] id) {
System.out.println("exe");
return new ArrayList<Blog>();
}
}
MBlogServiceImpl serviceBean = new MBlogServiceImpl();
Long[] params = new Long[]{1l};
Long param = new Long(1);
Method method = serviceBean.getClass().getMethod("queryBlogByIds",params.getClass());
Object obj = method.invoke(serviceBean,params);
System.out.println(obj);
{code}
其实method.invoke这行代码,eclipse编译的时候也会出现黄色警告:
The argument of type Long[] should explicitly be cast to Object[] for the invocation of the varargs method invoke(Object, Object...) from type Method. It could alternatively be cast to Object for a varargs invocation
把数据放在new Object[]{}就好了。
Object obj = method.invoke(serviceBean,new Object[]{params});
本文介绍如何在Java中使用反射机制正确调用带有数组参数的方法,解决因类型不匹配导致的问题,并给出具体示例。

1万+

被折叠的 条评论
为什么被折叠?



