开发者

Java: asterisk for loading classes

开发者 https://www.devze.com 2022-12-25 07:59 出处:网络
Is l开发者_如何转开发oading only the needed classes directly a good way of reducing the overall memory usage of a Java application?

Is l开发者_如何转开发oading 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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消