Wednesday, June 30, 2010

Locating the jar a class was loaded from

Here's a snippet of code to determine how to determine the jar that a class was loaded from:

private String getPath(Class cls) {
  String cn = cls.getName();
  String rn = cn.replace('.', '/') + ".class";
  String path = cls.getClassLoader().getResource(rn).getPat h();
  int ix = path.indexOf("!");
  if(ix >= 0) {
    return path.substring(0, ix);
  }
  else {
    return path;
  }
}

This can be invoked with with either of these methods:

String srcFile = getPath( MyClass.class );
or
Class myClass = Class.forName("class.namespace.MyClass");
  String srcFile = getPath( myClass );

Thanks to this link for the original version: http://www.techtalkz.com/java/102114-how-find-jar-file-ava-class-all-successorshad-been-loaded.html

No comments:

Post a Comment