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

≡放荡痞女 提交于 2019-11-28 11:49:21

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.

Paul Webster

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!