Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obscure Java import syntax? [closed]

I've come across obscure import syntax while looking at some source code from Sun's JVM implementation.

import java.awt;

From a look at the source code, this import statement appears to be importing the entire java.awt package, but the standard is to use a package wildcard: import java.awt.*;. However, the syntax of the import statement in ComponentFactory is invalid and does not compile with JDK or Eclipse.

Why would Java developers use this uncompilable syntax used, rather than the correct .* syntax? (Maybe the developers use a different compiler which supports this syntax?)

like image 248
FThompson Avatar asked Jan 31 '13 03:01

FThompson


2 Answers

Having looked at the latest JLS (http://docs.oracle.com/javase/specs/jls/se7/html/jls-7.html#jls-7.5.1), it says:

Example 7.5.1-3. No Import of a Subpackage

Note that an import statement cannot import a subpackage, only a type.

For example, it does not work to try to import java.util and then use the name util.Random to refer to the type java.util.Random:

import java.util;   // incorrect: compile-time error
class Test { util.Random generator; }

There is no reason that the language designers are using a different version of Java. They may have some secret tools for coding and testing, they might also test on some new features (but I don't think this is a new feature, as new features shouldn't be released like this without any description)

I believe it is the HTML formatting that automatically eliminates all the .* parts of import declarations.

like image 80
shuangwhywhy Avatar answered Sep 28 '22 00:09

shuangwhywhy


According to some documentation published by Oracle:

Note: Another, less common form of import allows you to import the public nested classes of an enclosing class. For example, if the graphics.Rectangle class contained useful nested classes, such as Rectangle.DoubleWide and Rectangle.Square, you could import Rectangle and its nested classes by using the following two statements.

import graphics.Rectangle;
import graphics.Rectangle.*;

Be aware that the second import statement will not import Rectangle.

However, after trying to import java.awt, I realized that this is not valid syntax because it is only a package a not a class. This leads me to believe that they published code that simply omits the .* after most of its imports to make the code appear slightly cleaner. Regardless, you can't write imports like this.

like image 40
supersam654 Avatar answered Sep 28 '22 00:09

supersam654