What's the syntax to import a class in a defau

2019-01-02 18:04发布

This question already has an answer here:

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?

5条回答
临风纵饮
2楼-- · 2019-01-02 18:46

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.

查看更多
永恒的永恒
3楼-- · 2019-01-02 18:51

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.

查看更多
宁负流年不负卿
4楼-- · 2019-01-02 19:00

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.

查看更多
步步皆殇っ
5楼-- · 2019-01-02 19:02

That's not possible.

The alternative is using reflection:

 Class.forName("SomeClass").getMethod("someMethod").invoke(null);
查看更多
有味是清欢
6楼-- · 2019-01-02 19:04

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.

查看更多
登录 后发表回答