在 Java 中的默认包中导入类的语法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2030148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the syntax to import a class in a default package in Java?
提问by Pops
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
是否可以在 Java 中导入默认包中的类?如果是这样,语法是什么?例如,如果你有
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
?
在另一个文件中。但是如果 SomeClass.java 不包含包声明呢?你会如何引用SomeClass
in AnotherClass
?
采纳答案by Dan Dyer
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.
从未命名的包中导入类型是编译时错误。
回答by Dan
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.
访问默认包中的类的唯一方法是从默认包中的另一个类。这种情况下,不用管它import
,直接参考就行了。
回答by OscarRyz
That's not possible.
那是不可能的。
The alternative is using reflection:
另一种方法是使用反射:
Class.forName("SomeClass").getMethod("someMethod").invoke(null);
回答by Rob H
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.
正如其他人所说,这是不好的做法,但是如果您因为需要与使用默认包的第三方库集成而别无选择,那么您可以在默认包中创建自己的类并访问其他班级那样。默认包中的类基本上共享一个命名空间,因此您可以访问另一个类,即使它驻留在单独的 JAR 文件中。只需确保 JAR 文件在类路径中即可。
This trick doesn't work if your class is not in the default package.
如果您的类不在默认包中,则此技巧不起作用。
回答by vishal rajput
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.
如果你对另一个包这样做,那么它应该是一个编译错误。