1

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.

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?

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.

Ingo
  • 36,037
  • 5
  • 53
  • 100

2 Answers2

6

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();
}

Not sure where it came from.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
3

The most reliable way when providing a plugin is to use org.osgi.framework.Bundle.getEntry(String) to get a URL to the jar file, and org.eclipse.core.runtime.FileLocator.toFileURL(URL) to return the absolute path to the jar in the filesystem.

Then you have a choice, either use that location for the java project classpath, or copy the jar into the java project workspace.

See https://stackoverflow.com/a/8337766/713646 for another example.

PW

Community
  • 1
  • 1
Paul Webster
  • 10,614
  • 1
  • 25
  • 32
  • Unfortunately, this does not work in Eclipse 3.7 at least, as it stands. Yet one can do `this.getBundle().getEntry("....")` where `this` is the class that derives from one of the abstract plugin classes. – Ingo Dec 14 '11 at 19:46
  • sorry for not making it clearer, but those are the FQNs of the classes involved. Yes, you either have to use your activator or `Platform.getBundle(*)` to get the bundle instance. – Paul Webster Dec 15 '11 at 16:19