开发Java程序时,能否用Java方法调用jdeps功能替代进程调用?
jdeps Process Calls Absolutely! You don’t have to rely on spawning external jdeps processes and parsing their output—the JDK provides native Java APIs to perform dependency analysis directly within your code. Here’s what you need to know:
Core API: com.sun.tools.jdeps Package
The official JDK includes the com.sun.tools.jdeps package (packaged as the jdk.jdeps module in Java 9+) which mirrors all the functionality of the jdeps command-line tool. This API lets you programmatically analyze class files, JARs, and modules for dependencies without leaving your Java code.
Key Notes for Different Java Versions
- Java 8 and earlier: The API lives in
tools.jar, located in your JDK’slibdirectory. You’ll need to add this JAR to your project’s classpath to access the API. - Java 9+: The API is part of the
jdk.jdepsmodule. To use it, declare a module dependency in yourmodule-info.java:requires jdk.jdeps;
Example: Analyze a JAR’s Dependencies
Here’s a simple snippet to replicate a basic jdeps myJar.jar call, capturing the output directly in your code:
import com.sun.tools.jdeps.JdepsTask; import java.io.PrintWriter; import java.io.StringWriter; public class JdepsApiDemo { public static void main(String[] args) { StringWriter outputCapture = new StringWriter(); PrintWriter writer = new PrintWriter(outputCapture); // Set up the dependency analysis task JdepsTask task = JdepsTask.newTask(); task.setOptions(new String[] {"path/to/your/target.jar"}); task.setOutput(writer); // Run the analysis boolean analysisSuccess = task.run(); if (analysisSuccess) { String dependencyReport = outputCapture.toString(); System.out.println("Dependency Analysis Result:\n" + dependencyReport); // Parse or process the report as needed for your application } else { System.err.println("Failed to complete dependency analysis"); } } }
More Advanced Usage
For finer-grained control (like filtering specific dependencies, analyzing module graphs, or inspecting individual class dependencies), you can use lower-level classes from the same package:
DependencyAnalyzer: Build and query detailed dependency graphsClassFileReader: Read metadata directly from class filesModuleDependencyAnalyzer: Handle module-specific dependency checks (Java 9+)
Important Caveats
- JDK-only availability: The
com.sun.tools.jdepsAPI is included in the JDK, not the JRE. If your app runs in a JRE-only environment, you’ll need to bundle the necessary JDK components or fall back to process calls as a backup. - Version compatibility: While the API is stable, minor changes can occur across JDK versions. It’s a good idea to test your code against all target JDK releases to avoid compatibility gaps.
内容的提问来源于stack exchange,提问作者JF Meier

