Share this page 

Obtain from where a Class is loadedTag(s): Language Varia

This HowTo detects where the class is coming from.
public class LoadingFromWhere {
  public static void main(String args[]){
    LoadingFromWhere s = new LoadingFromWhere();

  public void doit() {
    System.out.println(this.getClass().getName() + " is loaded from " +

    MyClass s = new MyClass();

class MyClass {
  MyClass() {
     (this.getClass().getName() + " is loaded from " +
The output
C:/temp>java LoadingFromWhere
LoadingFromWhere is loaded from file:/C:/temp/
MyClass is loaded from file:/C:/temp/
If running from a Jar
C:/temp>java -jar testing.jar
LoadingFromWhere is loaded from file:/C:/temp/testing.jar
MyClass is loaded from file:/C:/temp/testing.jar

Other technique

package com.rgagnon;

public class FromWhere {
  public static void main(String args[]){
    Class theClass = FromWhere.class; u = theClass.getResource("");
    System.out.println("This class (FromWhere) is located at : " + u);
This technique returns the package too, If the class is in the com.rgagnon package then the output is
C:/temp> java FromWhere
This class (FromWhere) is located at : file:/C:/temp/com/rgagnon
It doesn't work if running from a Jar, a null value is returned.

See these related HowTo's :

  • Get the "root" of an application
  • Determine if running from JAR