How to find the load location of a Java class file at run-time | Eklavya Online

How to find the load location of a Java class file at run-time

There are two ways to find it:

Using Classloader

Below code snippet can be used to find the location of java class



Using Protection Domain

We can use this to find the exact location a jar file containing the class JVM is using


How Java handles Two classes with same name in classpath

If I have two classes with same name say in two different jar in my classpath which one will be picked up by JVM , is there anyway I can suggest JVM to pick a specific one ?

Java interpreter loads classes based on the order they are specified in the CLASSPATH variable.
For example, lets say this is your classpath variable value


The Java interpreter will first look for MyClass class in the directory C:\Project\Dir1. Only if it doesn’t find it in that directory it will look in the C:\Project\Dir2 directory.

How to Add A Jar File To Java Load Path At Run Time

This can done by use of URLClassloader. A sample implementation of this code is shown below





public class SimpleJarLoader {


public static void main(String args[]) {

if (args.length < 2) {

System.out.println(“Usage: [Class name] [Jar Path]”);



try {

System.out.println(“Trying to load the class…”);


} catch (Exception ex) {

System.out.println(“Not able to load class…” + args[0]);



try {

String url = “jar:file:/” + args[1] + “!/”;

URL urls[] = { new URL(url) };

URLClassLoader cl = new URLClassLoader(urls,


System.out.println(“Looking into jar… ” + url);


System.out.println(“Woohoo….I found it”);

} catch (Exception ex) {

System.out.println(“Oops…Still cant find the jar”);





You can run this code by below command. (Make sure to use forward slash “/” as directory separator.)


java SimpleJarLoader org.springframework.core.SpringVersion C:/spring.jar


The output is like this


Trying to load the class…

Not able to load class…org.springframework.core.SpringVersion

Looking into jar… jar:file:/C:/spring.jar!/

Woohoo….I found it