Java - Can't import com.package.*(wildcard)

北慕城南 提交于 2019-12-04 03:42:44

问题


This may be a simple issue, but Google has returned nothing.

I have read Help with packages in java - import does not work

I still don't understand why a direct import will work but wildcard will not. [EDIT] By class package I mean a package of classes. I am still new to Java so I do not know the semantics [EDIT]

I have a class package: com.company.functions, when I try to import com.company.* I receive the following error.

java: package com.company does not exist

If I import com.company.function explicitly then I have no issues.

So I suppose that I have a solution but for the sake of learning, could someone explain why I see this issue?

IDE:IntelliJ IDEA 12

import com.sociapathy.*;  <--Throws compile error  java: package com.sociapathy does       not exist
import com.sociapathy.databaseAccess.MySQL;  <--Works just fine

回答1:


It sounds like you're trying to import a package that contains no classes, but only contains sub-packages.

i.e. You have classes in com.company.functions - e.g. com.company.functions.Foo
But no classes directly in com.company - e.g. com.company.Bar

Despite that fact that java packages appear to be hierarchical, for the purposes of imports, they aren't.

So, you cannot import com.company.* because it contains no classes of its own.
You can import com.company.functions.* because it does contain classes
And you can import com.company.functions.Foo because that is a class.

Now, you might be tempted create a Bar class in com.company. That would allow you to import com.company.*
But because imports are not treated hierarchically, that wouldn't cause classes in com.company.functions to be imported
You would still need to explictly import com.company.functions.Foo, or wildcard import com.company.functions.*




回答2:


In java, you can import an entire package:

import package.name.*;

Or you can import a specific member of a package

import package.name.class_name;

Don't confuse the dots in package names with the member access operator - they're just literal dots. You can't try to import multiple packages by breaking apart the package names.

import package.*;  //doesn't work
import packa*;  //doesn't work for the same reason


来源:https://stackoverflow.com/questions/16976064/java-cant-import-com-package-wildcard

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