如何使用 jar 以编程方式确定项目代码中依赖 jar 的路径?

How can I programmatically determine the path of depenency jar within the code of project using the jar?

我有两个 java 项目:ProjectA 和 ProjectB。 ProjectA 已经编译成jar 并设置为ProjectB 的依赖项。如何以编程方式确定 ProjectB 代码中 ProjectA.jar 的路径?

假设 foo 是来自 ProjectA 的 class 的实例:

foo.getClass().getProtectionDomain().getCodeSource().getLocation();

或者假设 FooProjectA 的 class :

Foo.class.getProtectionDomain().getCodeSource().getLocation();

应该给你罐子的位置。