Finding the path to a jar from a Class inside it?

后端 未结 2 1330
忘了有多久
忘了有多久 2020-12-10 23:27

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

相关标签:
2条回答
  • 2020-12-10 23:57

    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.

    0 讨论(0)
  • 2020-12-11 00:06

    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

    0 讨论(0)
提交回复
热议问题