Monday, January 21, 2008

Java: No Importing of Type from Unnamed Packages

There is a little corner case in Java that many Java developers may not run into very often if at all, but it can be frustrating when one does have to deal with it. The Java Language Specification (JLS) describes "unnamed packages" in Section 7.4.2 ("Unnamed Packages"). Sometimes referred to as the "default package" or the "anonymous package," the "unnamed package" refers to the package to which all compilation units (classes, interfaces, etc.) belong if they do not explicitly list a package. Most of us do not run into issues with the "unnamed package" because we tend to use named packages for our classes and interfaces. In fact, the Java Language Specification states that unnamed packages are primarily intended for beginning developers or for small, temporary Java applications.

The problem that I have run into with classes in unnamed packages is trying to access these classes from classes in explicitly named packages. In other words, when a third party provides classes without explicit package declaration, our classes in named packages cannot access those third party classes. Section 7.5 of the JLS explicitly states that a compiler error will result from trying to import a type from an unnamed package.

The most recent encounter I have had with this was when I tried to incorporate the JTop class that is delivered with Sun's Java SE 6 SDK as an example of using the JConsole Plugin. Neither the JTopPlugin class nor the JTop class has an explicitly named package and therefore both automatically are considered part of the unnamed package.

It is a relatively trivial manner to include the JTop functionality in one's own JConsole tab by importing JTop into one's JConsolePlugin class. However, this won't work "out of of the box" if one's JConsolePlugin class is declared as part of a named package. To make it work, one must either put one's own class in the unnamed package or else must make a minor modification to the JTop class to add a package declaration statement to the class. I prefer the latter. For example, I can add a package declaration statement like package jtop; at the top of the JTop.java file to make it part of a named package.

An interesting read related to a named package importing a type from an unnamed package is contained in the Bug 4361575 ("Correct scoping and diagnostics for import declarations") write-up. There is an explanation in there about importing an unnamed package's type from a named package. Perhaps more interesting is the reader feedback underneath the main bug entry. It is clear that this is not a very popular feature with Java developers, especially those who had code break during the transition from Java 1.3 to 1.4.

Another interesting read is top threads plugin for JConsole.

No comments: