Why does @RequestMapping annotation accept String parameter in java but not in scala?

狂风中的少年 提交于 2020-02-14 04:55:24

问题


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



来源:https://stackoverflow.com/questions/14323732/why-does-requestmapping-annotation-accept-string-parameter-in-java-but-not-in-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!