Warning for generic varargs

前端 未结 4 1949
暗喜
暗喜 2021-01-18 01:31

I have declared the following method:

private void mockInvokeDBHandler(Map... rows) {
    List> allRows         


        
相关标签:
4条回答
  • 2021-01-18 01:47

    You could lower the burden of using a List instead of varargs by using some builder interface (e.g. like the one I'm using). Using this CollectionBuilder, it would become something like this:

    mockInvokeDBHandler(CollectionBuilder.<Map<String, Object>>list().add(map1).add(map2).get());
    

    it's prettier without generic args though:

    import static at.molindo.utils.collections.CollectionBuilder.list
    
    List<String> list = list(String.class).add("foo").addAll(set).get();
    

    It's certainly longer as the varargs solution, but anyway pretty handy at times.

    0 讨论(0)
  • 2021-01-18 01:54

    There's no way to avoid this warning, other than adding @SuppresWarning("unchecked") to the method :)

    Since you say it's a private method there's no "clients" in this case and you're in control of the method, so ignoring the warning seems reasonable.

    A few times when I've created methods taking parameterized types as a varargs parameter, I've created some overloads:

    void mockInvokeDBHandler(Map<String, Object> map1)
    void mockInvokeDBHandler(Map<String, Object> map1, Map<String, Object> map2)
    void mockInvokeDBHandler(Map<String, Object> map1, Map<String, Object> map2, Map<String, Object>... othermaps)
    

    That could avoid some of the warnings, depending on how many arguments are supplied.

    0 讨论(0)
  • 2021-01-18 02:00

    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).

    0 讨论(0)
  • 2021-01-18 02:01

    For anyone landing here, the answers are a little old. Java 7 introduced the @Safevarargs annotation to address this:

    @SafeVarargs
    private void mockInvokeDBHandler(Map<String, Object>... rows) {
    

    From the javadoc:

    A programmer assertion that the body of the annotated method or constructor does not perform potentially unsafe operations on its varargs parameter. Applying this annotation to a method or constructor suppresses unchecked warnings about a non-reifiable variable arity (vararg) type and suppresses unchecked warnings about parameterized array creation at call sites.

    0 讨论(0)
提交回复
热议问题