0

There is something called custom class loader where we can write and load the load the same class (which was loaded by the Java class loader).

My question is, why we have to go for a custom class loader? What are the real time situations or use cases for this?

k_ssb
  • 6,024
  • 23
  • 47

1 Answers1

0

Here's a short and sweet answer: Custom class loader allows you to control how Java classes are loaded in the JVM, based on your application specific needs. For example, JBoss' hot deployment (other containers support this functionality too) uses custom class loaders to swap out classes, head over to this if you want to know more or http://tomcat.apache.org/tomcat-6.0-doc/class-loader-howto.html

EDIT

As ask by OP, here's a small example with code snippet to just give an idea about custom class loader.

Relying on JVM’s class loader one cannot load two different versions of the same JDBC driver. So how to get around this problem? The answer lies in making a custom class loader and loading classes directly from JAR archives.

import java.net.*;

URL url=new URL("jar:file:/c:myJarsmyJar1.jar!/");
URLClassLoader ucl = URLClassLoader(new URL[] { url });
Object myClassObject = Class.forName("MyClass", true, ucl).newInstance();

Above example illustrates how to load java classes from their respective jar files using URLClassLoader, there are other ways and API's also available to do that like JARClassLoader etc.

foxt7ot
  • 2,465
  • 1
  • 19
  • 30
  • Suppose if there are two class loaders and same class is loaded by both class loader. How can I differentiate different classes loaded by different loaders. Please post with example program – Vaithilingam K May 16 '18 at 11:08
  • Hi @VaithilingamK, Sorry for posting answer a little late, Hope you will get the idea from my example. If this solves your query then kindly mark answer as solution. Thanks – foxt7ot May 21 '18 at 06:01