Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Finding Out Where Your Class Files Are

DZone's Guide to

Finding Out Where Your Class Files Are

· Java Zone
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

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

Download Modern Java EE Design Patterns: Building Scalable Architecture for Sustainable Enterprise Development.  Brought to you in partnership with Red Hat

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}