从里面的 Class 中找到 jar 的路径?

2022-01-16 00:00:00 eclipse-plugin java eclipse classpath

插件 x.y.z 应该在 Java 项目之上运行并生成一些 Java 代码.此代码将需要在构建和运行时插件 jar 中可用的类.因此,插件的 jar(或安装目录)应该出现在构建类路径中.

Plugin x.y.z is supposed to run on top of a Java project and generate some Java-Code. This code will need classes available in the Plugin's jar at build and run time. Hence, the Plugin's jar (or installation directory) should appear in the build classpath.

插件如何以可移植的方式找到它自己的 jar/安装目录的确切路径,或者就此而言,某个关联插件的 jar 的路径?

How can a plugin find out the exact path of it's own jar/installation directory, or, for that matter, the path to the jar of some associated plugin in a portable way?

背景是我想制作一个用户可以运行以启用 x.y.z 的向导.项目的性质.应该为用户提供一个有意义的默认值,以便在哪里可以找到所需的运行时功能,并且给定的库将被添加到构建路径中.

Background is I want to make a wizard that the user can run to enable x.y.z. nature on a project. The user should be provided with a meaningful default for where to find the required runtime functionality, and the given library will be added to the build path.

推荐答案

我们用这个来查找类的位置:

We use this to find the location of a class:

public static URL getLocation(final Class cls) {
  final ProtectionDomain pd = cls.getProtectionDomain();
  final CodeSource cs = pd.getCodeSource();
  return cs.getLocation();
}

不确定它来自哪里.

相关文章