Difference between revisions of "Obtain from where a Class is loaded"

From CodeCodex

(Java)
Line 24: Line 24:
 
}
 
}
 
</highlightsyntax>
 
</highlightsyntax>
<highlightsyntax language="java122">
 
 
The output
 
The output
 +
<pre>
 
>java LoadingFromWhere
 
>java LoadingFromWhere
 
LoadingFromWhere is loaded from file:/C:/temp/
 
LoadingFromWhere is loaded from file:/C:/temp/
 
MyClass is loaded from file:/C:/temp/
 
MyClass is loaded from file:/C:/temp/
 +
</pre>
 
Other technique (doesn't work with jar)
 
Other technique (doesn't work with jar)
</highlightsyntax>
 
  
 
<highlightsyntax language="java122">
 
<highlightsyntax language="java122">
Line 42: Line 42:
 
}
 
}
 
</highlightsyntax>
 
</highlightsyntax>
<highlightsyntax language="java122">
 
 
The output
 
The output
 +
<pre>
 
> java FromWhere
 
> java FromWhere
 
This class (FromWhere) is located at : file:/C:/temp/
 
This class (FromWhere) is located at : file:/C:/temp/
</highlightsyntax>
+
</pre>
 
[[Category:Java]]
 
[[Category:Java]]

Revision as of 22:53, 16 August 2009

Implementations

Java

<highlightsyntax language="java122"> 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());
 }

} </highlightsyntax> 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)

<highlightsyntax language="java122">

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

} </highlightsyntax> The output

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