java反射调用时,参数是数组的问题


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});

猜你喜欢

转载自san-yun.iteye.com/blog/1689078