What is an “import” called?

2019-02-21 20:09发布

问题:

It is not a statement nor an expression.

What is that called then? A directive?

回答1:

"declaration"

See also

  • JLS 7.5. Import Declaration
    • 7.5.1 Single-Type-Import Declaration
    • 7.5.2 Type-Import-on-Demand Declaration
    • 7.5.3 Single Static Import Declaration
    • 7.5.4 Static-Import-on-Demand Declaration


回答2:

It's called a Declaration.



回答3:

In the general scope, it is a directive.

Within Java, classes have a tight relationship between their declaration and their containing file (known as a compiler unit in Java's architecture). However, the import statement pre-dates Java.

When it was used in the C language, it was a declaration to the pre-processor (a component that is not existent in Java, to "paste" the file at "this location". This allowed one to "use" declarations without defining them (important for structuring C source code) by pasting in the "header" file which contained all the declarations for an "definition" file which would be linked in at a later date. This style of layout allowed implementations to share each others declared types without being influence by the actual implementation (known as the type definition).

Java inherited from C's legacy, so they used the "import" keyword to locate the type declaration; but Java doesn't really have independent declarations and definitions, opting for the declaration to be "read" from the definition. This was in an attempt to prevent a common C / C++ failure (that of compiling against on version of declarations, to have the code mysteriously fail with an almost-the-same set of definitions (built off a newer or later version of declarations).

So, for C/C++ - A preprocessor directive (equivalent to a preprocessor command).

And for Java - A declaration, as the directive matches a command to a preprocessor that no longer exists, under a restrictive layout that only permits one declaration per included file.