Finding out where your class files are

[2010-04-29] dev, hack, java
(Ad, please don’t block)

Sometimes, when you are writing a program, you need to install data (e.g. by unzipping example files) or to find additional data (e.g. plugins). If you know the location of your class files, you can put the data close to them or start your search there. Your program will usually be packaged as a JAR file, so this scheme allows you to keep everything in the same directory. But any solution should also work for unarchived files, because you want to test while developing your (un-jarred) code. Until now, I’ve always used hacks involving Class.getResource() and looking for exclamation marks in the returned URL to find out if the program is currently running from a JAR. Recently, I’ve discovered a simpler solution (source):

ProtectionDomain protectionDomain = HyenaDesk.class.getProtectionDomain();
For example, this code computes the following two values for codeLoc.
  • Unarchived: /home/rauschma/workspace/hyena_desk/bin
  • JAR: /home/rauschma/workspace/hyena_desk/build/hyena_desk.jar

Most popular (last 30 days)