What do square brackets in Java method declarations mean?

前端 未结 5 1280
死守一世寂寞
死守一世寂寞 2021-01-06 05:12

The grammar for method declarations in Java is something like the following:

Java method declaration BNF:

method_declaration 
    ::= 
    { modifier         


        
5条回答
  •  [愿得一人]
    2021-01-06 05:42

    It is a legacy construct. From the JLS (§8.4. Method Declarations):

    For compatibility with older versions of the Java SE platform, the declaration of a method that returns an array is allowed to place (some or all of) the empty bracket pairs that form the declaration of the array type after the formal parameter list. This is supported by the following obsolescent production, but should not be used in new code.

    MethodDeclarator:
         MethodDeclarator [ ]
    

    Thus, it is valid Java (even though I've never seen this construct used in real code).

    As to the grammar you quote, it seems incomplete. For example, it doesn't seem to include the optional throws clause. Also, it only allows a single pair of square brackets in method_declaration whereas the official grammar allows any number of such pairs.

    The definitive reference is the Java Language Specification, Chapter 18. Syntax.

提交回复
热议问题