Thursday, September 29, 2011

Location of java class file used by Application


Sometimes, while debugging the code, you will be wondering that which class is being picked by Java application from the current Classpath.
Here is some small code snippet to know the location of the class file.
Very simple, it just tries to get the system resource for the class file.

package test.java;

public class ClassSource {

    public static String getClassLocation(String fullQualifiedclassName) throws ClassNotFoundException {
        Class cls = Class.forName(fullQualifiedclassName);
        String classPath = fullQualifiedclassName.replace('.','/').concat(".class");
        if (cls!=null && cls.getClassLoader()!=null) {
            return cls.getClassLoader().getResource(classPath).toString();
        } else {
            return ClassLoader.getSystemResource(classPath).toString();
        }
          
    }
    
    public static void main(String[] args) throws Exception {
        System.out.println("Class Object source : " + getClassLocation("java.lang.Object"));
        System.out.println("Current Class : " + getClassLocation("test.java.ClassSource"));
    }
    
}

Output on my machine:

Class Object source : jar:file:/L:/Program%20Files/Java/jre1.5.0_09/lib/rt.jar!/java/lang/Object.class
Current Class : file:/I:/work/eclipse-workspace/Java-Test/classes/test/java/ClassSource.class

No comments:

Post a Comment