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:
Post a Comment