Platinum Partner
java

Finding Out Where Your Class Files Are

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();
File codeLoc = new File(protectionDomain.getCodeSource().getLocation().getFile());

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

From http://2ality.blogspot.com/2010/04/finding-out-where-your-class-files-are.html

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}