Wednesday, January 16, 2008

Finding from where the java class is loaded

When programming java often times you end up in situation were whatever changes you made to the class is no reflecting when you run the code. Every time when I end up in this situation I knew that there is an old version of my class sitting some where and getting loaded in to the class path. Many of the time, you can figure out this by examining the java classpath. But most of the time the class is loaded from one of the old jar files that you don’t want to load.

To know from where the class is loaded; you can use the below code snippet

public String getClassLocation()


String className= this.getClass().getName();

className = className.replace('.', '/');

className = '/' + className + ".class"; classUrl = this.getClass().getResource(className);

String arr [] = classUrl.getFile().split ( "!") ;

return arr[0].replaceFirst("file:/","");


The getClassLocation function will work for any of your class and it will return the absolute path of the class file with the file name from where the class is loaded.

No comments: