What's the syntax to import a class in a default package in Java?

Is it possible to import a class in Java which is in the default package? If so, what is the syntax? For example, if you have

package foo.bar;


public class SomeClass {
// ...

in one file, you can write

package baz.fonz;


import foo.bar.SomeClass;


public class AnotherClass {
SomeClass sc = new SomeClass();
// ...

in another file. But what if SomeClass.java does not contain a package declaration? How would you refer to SomeClass in AnotherClass?

135646 次浏览

You can't import classes from the default package. You should avoid using the default package except for very small example programs.

From the Java language specification:

It is a compile time error to import a type from the unnamed package.

The only way to access classes in the default package is from another class in the default package. In that case, don't bother to import it, just refer to it directly.

That's not possible.

The alternative is using reflection:

 Class.forName("SomeClass").getMethod("someMethod").invoke(null);

As others have said, this is bad practice, but if you don't have a choice because you need to integrate with a third-party library that uses the default package, then you could create your own class in the default package and access the other class that way. Classes in the default package basically share a single namespace, so you can access the other class even if it resides in a separate JAR file. Just make sure the JAR file is in the classpath.

This trick doesn't work if your class is not in the default package.

It is not a compilation error at all! You can import a default package to a default package class only.

If you do so for another package, then it shall be a compilation error.