简体   繁体   中英

Java: asterisk for loading classes

Is loading only the needed classes directly a good way of reducing the overall memory usage of a Java application?

For example:

import java.awt.Graphics;

vs

import java.awt.*;

No. You should import only the needed classes to make it clear to programmers which classes are actually needed by your class.

Import statements just tell the compiler where to look for the classes you are using - it doesn't mean all the classes in the package are loaded into memory.

To put it simply: no.

import statements aren't translated into any form of bytecode. They're just shortcuts to avoid using (ugly!) fully qualified type names.

As others have put it, imports are used by the compiler only. You COULD write your whole program without any imports by using the full names of everything, but that would quickly grow rather big.

java.io.InputStream is = new java.io.FileInputStream(new java.io.File("foo"));

The star-import is to make it less tedious to write all the import statements by hand, but result in too many things being imported, so that the compiler have more than one possibility. Modern IDE's like Eclipse therefore import everything one-by-one so this cannot happen.

Did you mean star imports like import pack.*; ?

In Java, it has nothing do with memory usage, import is only used to change how you reference the classes. However, there are coding practice concerns regarding star imports.

I generally use fully-qualified type names, rather than such large statements. Packages exist for a reason, and it's because the developer of that package likely filled his package namespace with all sorts of crap that you don't like, and you just want that class.

Explicitly importing the classes you need vs doing a *-import makes no difference. The JVM only loads what you end up using and nothing more.

Having said that, explicitly importing your classes is a good software design decision (and *-import is the sign of slackers who don't know or care about good software design principles... I'm not joking, I'm dead serious.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM