Why does @RequestMapping annotation accept String

2020-03-18 07:11发布

问题:

Reading the @RequestMapping documentation : http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/bind/annotation/RequestMapping.html

It accepts a String array parameter for its path mapping.

So this works using java :

@RequestMapping("MYVIEW")

but in scala I need to use :

@RequestMapping(Array("MYVIEW"))

The scala version makes sense as the annotation expects a String array. But why does above work in java, should it not give a compile time error ?

Below class 'ArrayChecker' (a class I wrote to illustrate this point) causes a java compile time error :

The method acceptArrayParam(String[]) in the type ArrayChecker is not applicable for the arguments (String)

public class ArrayChecker {

    public static void main(String args[]){

        String[] strArray;

        acceptArrayParam("test");
    }

    private static void acceptArrayParam(String[] param){

    }
}

Should a similar error not be caused by @RequestMapping("MYVIEW") ?

回答1:

Section 9.7.1 of the Java SE specification states:

If the element type is an array type and the corresponding ElementValue is not an ElementValueArrayInitializer, then an array value whose sole element is the value represented by the ElementValue is associated with the element. Otherwise, if the corresponding ElementValue is an ElementValueArrayInitializer, then the array value represented by the ElementValueArrayInitializer is associated with the element.

With a comment clarifying the above stating:

In other words, it is permissible to omit the curly braces when a single-element array is to be associated with an array-valued annotation type element.

Because Scala has no equivalent array initializer syntax, you must use Array(elems).



回答2:

This is part of the language specification for annotations that use the default value element.

See JLS 9.7.3 for examples, including one with the comment "Note that the curly braces are omitted."