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

com.fromdev.MyClass
this.getClass().getClassLoader().getResource(“com/fromdev/MyClass.class”)

 

Using Protection Domain

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

clazz.getProtectionDomain().getCodeSource().getLocation()

How Java handles Two classes with same name in classpath

If I have two classes with same name say MyClass.java 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

C:\Project\Dir1;C:\Project\Dir2

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

 

import java.net.URL;

import java.net.URLClassLoader;

 

public class SimpleJarLoader {

 

public static void main(String args[]) {

if (args.length < 2) {

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

return;

}

try {

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

Class.forName(args[0]);

} 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,

SimpleJarLoader.class.getClassLoader());

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

cl.loadClass(args[0]);

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

} catch (Exception ex) {

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

ex.printStackTrace();

}

}

}

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