How to import two classes with the same name in different packages?

隐身守侯 提交于 2019-12-08 19:21:24

问题


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.

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?


回答1:


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.




回答2:


The only purpose of an import statement is to establish a shorthand alias for a fully-qualified name. 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.




回答3:


The existing answers are correct. I'd like to show you how class name conflicts can be handled in Kotlin (docs).

If there is a name clash, we can disambiguate by using as keyword to locally rename the clashing entity:

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.



来源:https://stackoverflow.com/questions/3731125/how-to-import-two-classes-with-the-same-name-in-different-packages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!