Accessing classes in default package in a JAR file

2019-06-28 06:52发布

问题:

I have a Java application and the Java files are in a package called app. I have added a JAR file to the classpath. All classes in the JAR file are in the default package.

From my Java application I can't access classes of this JAR file. Only if I put my application files in the default package, then I can see the classes in the JAR file. Why is that?

回答1:

You can no longer import from default packages. (You used to be able to in Sun's early javac implementations, but this was not allowed for in the language spec.) Obvious solutions:

  • Don't use the default package, if possible. Move all classes, interfaces and enums into named packages. [good]
  • Move your packaged classes into the default package. [bad]
  • Access the classes via reflection. [terrible]


回答2:

Classes in the default package are not visible to classes inside a package.

When classes are in a different package, then you basically need to import classes. But since it's impossible to import classes in the default package, the only solution is to put those classes in a package.

Always put classes in a package whenever you want to reuse classes.



标签: java jar package