通用可变参数警告 [英] Warning for generic varargs

查看:355
本文介绍了通用可变参数警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经声明了以下方法:

pre $ private $ mockInvokeDBHandler(Map< String,Object> ... rows){
List< Map< String,Object>> allRows = Arrays.asList(rows));
//省略方法的其余部分
}

它由客户端使用类似于

  Map< String,Object> row1 = new HashMap< String,Object>(); 
地图< String,Object> row2 = new HashMap< String,Object>();

mockInvokeDBHandler(row1,row2);

但是,上面显示的最后一行会生成一个警告:


类型安全性:为可变参数参数创建一个通用的Map数组

I don不完全理解这一点,但我想这是因为可变参数被转换为数组,因此有一个数组的类型是一个泛型类是一个坏主意(因为泛型不变,而数组不是)。



我可以通过将方法重新定义为

来解决此问题。

  private void mockInvokeDBHandler(List< ; Map< String,Object>> rows){
}

将行对象放入客户端的List中,我宁愿避免这种负担。有没有更好的解决方案?

解决方案

要将参数传递给varargs方法,编译器会将参数放入数组中。 / p>

警告是让您知道编译器无法保证数组中的每个元素(varags方法的每个参数)都是真正的 Map< String,Object>



这是一个恼人的警告,因为你无法解决这个问题,而不是重新定义方法签名而不使用可变参数。海事组织,只要你确定这些参数的实际运行时类型(在这种情况下,你是),就可以忽略。


I have declared the following method:

private void mockInvokeDBHandler(Map<String, Object>... rows) {
    List<Map<String, Object>> allRows = Arrays.asList(rows));
    // rest of method omitted
}

It is invoked by clients using something like

Map<String, Object> row1 = new HashMap<String, Object>();
Map<String, Object> row2 = new HashMap<String, Object>();

mockInvokeDBHandler(row1, row2);

However, the last line shown above generates a warning

Type safety : A generic array of Map is created for a varargs parameter

I don't fully understand this, but I guess it's because varargs params are converted to arrays, and it's a bad idea to have an array whose type is a generic class (because generics are invariant, whereas arrays aren't).

I could resolve this problem by redifining the method as

private void mockInvokeDBHandler(List<Map<String, Object>> rows) {
}

But this places the burden of putting the row objects into a List on the client, which I'd rather avoid. Is there a better solution?

解决方案

To pass the arguments to a varargs method the compiler will place the arguments into an array.

The warning is to let you know that the compiler cannot guarantee that each of the elements in the array - each of the arguments to the varags method - is truly a Map<String, Object>.

This is a bit of an annoying warning because there is no way you can work around this, other than to redefine the method signature to not use varargs. IMO it is safe to ignore as long as you are pretty sure of the actual run-time types of these arguments (which in this case, you are).

这篇关于通用可变参数警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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