Use of * in Import Statement in Java [duplicate]

2019-03-06 03:53发布

This question already has an answer here:

Can someone explain me the import statements in Java. Some import has * suffixed to it and some doesn't. What is the difference between these two? Does the use of * in the import statement imports all the classes?

see here import

Here they have said that though the import statements seems nested they are not so. Can someone explain in detail?

标签: java import
4条回答
Rolldiameter
2楼-- · 2019-03-06 04:13

From your link:

import java.util.*;

The * is a "regular expression operator" that will match any combination of characters. Therefore, this import statement will import everything in java.util. If you have tried entering and running the example program above, you can change the import statement to this one.

So yes * suffix imports all classes in this path

查看更多
虎瘦雄心在
3楼-- · 2019-03-06 04:20

The use of * is considered a bad practice. It is used to import all files within that package. The more correct way of doing this is listing off each of the classes that you need, specifically in a scenario where you are doing a code review outside of an IDE and need to know which version of the class you are using. Essentially it breeds laziness in the development team.

Comment

For those arguing that this is not a "bad" practice as I have stated. How can you possibly say that this is a good practice?

import java.util.*;  
import java.io.*;

Even if the compiler ignores everything under the * except the List that you have imported, how does this possibly help someone looking at the code in the future? I think a good deal of people here forget that you are writing code for humans and not the computer. Further how could you possibly convert this code when Java goes away and you are using SuperAwesomeLanguage? Given the following example please convert this to your new language when you have ZERO knowledge of java:

public class Foo  
{
    private List list;
}

Is List in io? is io even required? The issue is you don't know. So by being explicit you can guide future developers as to what classes are required.

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-03-06 04:20

Does the use of * in the import statement imports all the classes

Yes.

From Oracle's Documentation :

A type-import-on-demand declaration allows all accessible types of a named package or type to be imported as needed.

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-03-06 04:29
import com.example.*

Imports all classes in the com.example package

import com.example.ClassName

Imports just the ClassName class

查看更多
登录 后发表回答