简体   繁体   中英

How can I Identify which package classes are in use in my program?

I have imported packages using * .

Example:

import java.awt.*;

Is there a way to find out which classes of this package I am actually using in my program? I need to import only the classes I am actually using for my Java Project.

Thank you

Use an IDE like Eclipse to organize the imports, which will only add imports for classes that are used in the code.

The shortcut for Eclipse is Ctrl + Shift + O (you can even configure to run the action automatically on saving changes to a file).

For IntelliJ, Ctrl + Alt + O .

If you just want to clean up your * imports, the keyboard shortcuts in the other answers will do it, but if you want to be able to automatically find out what dependencies are used by some code, Oracle has created a tool called jdeps that comes with the JDK. It is described as:

The jdeps command shows the package-level or class-level dependencies of Java class files. The input class can be a path name to a .class file, a directory, a JAR file, or it can be a fully qualified class name...

For example, if your classes are built to a classes directory, the following command would show you what classes are used by class com.example.Foo :

jdeps -verbose:class -cp classes com.example.Foo

See the jdeps documentation for details on usage.

you can use reflection (getPackage() or getClassName()) for the package details.

try {

    System.out.println(Class.class.forName("java.lang.Integer").getPackage());
 }
 catch(ClassNotFoundException ex) {
    System.out.println(ex.toString());
 }

It is good practice not to use * for imports unless you will be using each and every one. This will keep the executable from being unnecessarily large.

Like @Bill the Lizard said, the compiler will let you know which imports you forgot to add.

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