Does an import wildcard import everything all the

2019-02-18 23:07发布

问题:

I was working on a little Java program and was using arrays so I had done:

import java.util.Arrays;

Later I started expanding on what I had previously done and decided I wanted to get input from the user, so at that point I added:

import java.util.Scanner;

Now a thought occurred. I know that I could just do:

import java.util.*

Then I'd just need 1 import line instead of two (or however many I end up needing), but does the wildcard in the import mean that it will import everything from that package regardless of if it's needed or not, or will only the selective functionality be pulled?

My instinct here is to write more code and only include the packages I know I need, but if it doesn't make a difference why would anyone import more levels/packages then they need to? (I'd rather just be lazy and write less code)

回答1:

Be clear about what import is doing. It does NOT mean loading .class files and byte code.

All import does is allow you to save typing by using short class names.

So if you use java.sql.PreparedStatement in your code, you get to use PreparedStatement when you import java.sql.PreparedStatement. You can write Java code forever without using a single import statement. You'll just have to spell out all the fully-resolved class names.

And the class loader will still bring in byte code from .class files on first use at runtime.

It saves you keystrokes. That's all.

It has nothing to do with class loading.

Personally, I prefer to avoid the * notation. I spell each and every import out. I think it documents my intent better. My IDE is IntelliJ, so I ask it to insert imports on the fly.

Laziness is usually a virtue for developers, but not in this case. Spell them out and have your IDE insert them for you individually.

if you type

import java.util.*;

you'll get to refer to Scanner and List by their short names.

But if you want to do the same for FutureTask and LinkedBlockingQueue you'll have to have this:

import java.util.concurrent.*;


回答2:

The wildcard imports everything in that package. However, use an IDE like Eclipse and it offers you the possibility to organize the imports.



回答3:

The wildcard imports all classes and interfaces in that package.

However, the wildcard import does not import other packages that start with the same name.

For example, importing java.xml.* does not import the java.xml.bind package.