What is the proper style for listing imports in Java?

前端 未结 10 1066
梦谈多话
梦谈多话 2021-02-18 16:01

Is it better to list each individual piece of a package you\'re going to need (see #1) or is it better to just import everything from a package (see #2)?

1



        
10条回答
  •  无人及你
    2021-02-18 16:28

    It's NOT simply a matter of style; import-on-demand can result in code that ceases to compile as new classes are added to existing packages.

    Basic idea (See http://javadude.com/articles/importondemandisevil.html for details.):

    import java.awt.*;
    import java.util.*;
    ...
    List list;
    

    worked in Java 1.1; as of Java 1.2, the above code will no longer compile.

    Import on demand is EVIL because your program can stop compiling when new classes are added to existing packages!

    ALWAYS use explicit imports. It's not a matter of style; it's a matter of safety.

    This is especially bad if you check in perfectly-compiling code and a year later someone checks it out and tries to compile it with new class libraries.

    (Import-on-demand is an example of a really bad programming language feature - no feature should break code when new types are added to a system!)

提交回复
热议问题