Real'sHowTo AddThis Feed Button
Custom Search

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


public class LoadingFromWhere {
  public static void main(String args[]){
    LoadingFromWhere s = new LoadingFromWhere();
    s.doit();
  }

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

    MyClass s = new MyClass();
  }
}

class MyClass {
  MyClass() {
    System.out.println
     (this.getClass().getName() + " is loaded from " +
     this.getClass().getProtectionDomain().getCodeSource().getLocation());
  }
}
The output
>java LoadingFromWhere
LoadingFromWhere is loaded from file:/C:/temp/
MyClass is loaded from file:/C:/temp/

Other technique (doesn't work with jar)

public class FromWhere {
  public static void main(String args[]){
    Class theClass = FromWhere.class;
    java.net.URL u = theClass.getResource("");
    System.out.println("This class (FromWhere) is located at : " + u);
    }
}
The output
> java FromWhere
This class (FromWhere) is located at : file:/C:/temp/
See these related HowTo's : 1  2
blog comments powered by Disqus


If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2013
[ home ]