Friday, 14th October 2011
Follow WikiJava on twitter now. @Wikijava

Obtain from where a Class is loaded

From WikiJava

Jump to: navigation, search


This tutorial contains two methods to dinamically find where a class is loaded from.

Contents

the article

There are two ways to obtain from where a class is loaded,

first method

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());
  }
}

gives as output

>java LoadingFromWhere
LoadingFromWhere is loaded from file:/C:/temp/
MyClass is loaded from file:/C:/temp/


second method

this method doesn't work with Jars.

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);
    }
}

gives as output

> java FromWhere
This class (FromWhere) is located at : file:/C:/temp/

See Also

Real's Java How To

Comments from the users

To be notified via mail on the updates of this discussion you can login and click on watch at the top of the page


Comments on wikijava are disabled now, cause excessive spam.