header

Torsten Curdt’s weblog

Where is this java class from?

Recently James blogged about a nice addition to log4j. The submission even got applied already.

It uses the same “trick” that I had stashed away in my “toblog” folder and almost had forgotten about. Finding out the what jar file a class comes from can be quite useful at times. The straight forward approach is to lookup the resource and go from there.

Class type = yourinstance.getClass();
File jar = new File(type.getClassLoader().getResource(
  type.getName().replace('.', '/') + ".class")
  .toExternalForm()
  .replaceFirst("^[^/]*", "")
  .replaceFirst("!.*", ""));

But a much simpler and faster approach is to use the ProtectionDomain (if available).

Class type = yourinstance.getClass();
File jar = new File(type.getProtectionDomain()
  .getCodeSource().getLocation()
  .toURI());

Really quite simple but useful.

    blog comments powered by Disqus