Over a million developers have joined DZone.
Silver Partner

Finding Out Where Your Class Files Are

· Java Zone

The Java Zone is brought to you in partnership with JetBrains.  Learn about instant and clever code completion, on-the-fly code analysis and reliable refactoring tools with IntelliJ IDEA.

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

The Java Zone is brought to you in partnership with JetBrains.  Learn about instant and clever code completion, on-the-fly code analysis and reliable refactoring tools with IntelliJ IDEA.

Topics:

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

{{ parent.tldr }}

{{ parent.urlSource.name }}