How do I determine a class's file location at runtime?

Paul MacDougall

This method returns a URL to the class file in question. From that you can manipulate it to get what you want.

  public java.net.URL locateClass(Class pClass){
    // get the name of the class (e.g. my.package.MyClass)
    String className = pClass.getName();
    
    // create the resource path for this class
    String resourcePath = "/" + className.replace('.','/') + ".class";
    
    // get the resource as a url (e.g. file:/C:/temp/my/package/MyClass.class
    java.net.URL classURL = pClass.getResource(resourcePath);

    return classURL;
  }
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact