简体   繁体   中英

ambiguity regarding Java's import syntax

while preparing for the JCA exam I just came across this snippet

import java.lang.String.*; 
class EJava 
{
String guru; 
}

This is of course nonsense code as java.lang is imported by default. Anyway, the author wants to use it to make the point that this code won't compile as it uses an incorrect import syntax.

The code does compile, though. So is it just the case that an import using a wildcard can simply mean two things?

import somepackage.*; // import any type in the package somepackage 

import somepackage.type.*; // import any member of this type (equivalent to : import somepackege.type;)

This would definitely compile, but the statement will import all public nested classes in the java.lang.String class and unfortunately there are none.

So effectively the statement is useless yet harmless. There should be no problem in compilation.


If you were using static import, the case would have been different, as there are many static methods in String class.

From the Java Language Specification

A type-import-on-demand declaration allows all accessible types of a named package or type to be imported as needed.

[...]

A static-import-on-demand declaration allows all accessible static members of a named type to be imported as needed.

So your

import java.lang.String.*; 

would import all accessible types in String (there are no accessible ones in Oracle JDK 8). A static import would import all accessible static members, including methods .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM