[英]How to import two classes with the same name in different packages?
I want to import these two classes, both named Query
- one a JDO class, the other a JPA class, to use in different methods in the same class. 我想导入这两个类(都命名为Query
-一个是JDO类,另一个是JPA类,以便在同一类的不同方法中使用。
import javax.jdo.Query;
import javax.persistence.Query;
Is there a way to globally import both of them at the same time at the top of the file? 有没有办法同时在文件顶部同时全局导入这两个文件?
I'm afraid, no. 恐怕不行。 But you don't have to import class to use it: just reference one of the classes by its full name, like 但是您不必导入类即可使用它:只需按其全名引用其中一个类,例如
javax.jdo.Query query = getJDOQuery();
query.doSomething();
Then you can import another without name collisions. 然后,您可以导入另一个没有名称冲突的文件。
BTW, sometimes if you start getting lots of such name such collisions in your class, it's a subtle hint for refactoring: splitting functionality of one big class between several small ones. 顺便说一句,有时候,如果您在类中开始遇到诸如此类的冲突之类的话,这是重构的微妙暗示:将一个大类的功能拆分为几个小类。
The only purpose of an import
statement is to establish a shorthand alias for a fully-qualified name. import
语句的唯一目的是为标准名称建立简写别名。 If you were allowed to imported both, you'd create an ambiguity that would require type inference to resolve, and make your code extremely difficult to read. 如果允许您同时导入这两个代码,则将造成歧义性,需要类型推断来解决,并使代码极难阅读。
The existing answers are correct. 现有答案是正确的。 I'd like to show you how class name conflicts can be handled in Kotlin ( docs ). 我想向您展示如何在Kotlin( docs )中处理类名冲突。
If there is a name clash, we can disambiguate by using as
keyword to locally rename the clashing entity: 如果存在名称冲突,我们可以使用as
关键字在本地重命名冲突实体来消除歧义:
import javax.jdo.Query // Query is accessible
import javax.persistence.Query as jpaQuery // jpaQuery stands for 'javax.persistence.Query'
That's +1 reason why you should consider Kotlin for your next project. 这就是为什么您应该在下一个项目中考虑Kotlin的+1原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.