Custom ClassLoaders In Java

We are going to Write our Own Custom ClassLoaders in Java, but before we start on this topic.Let’s take a while to understand Why do We need Custom ClassLoaders?

Why Custom ClassLoaders:-

As you know from my previous post JVM has its own ClassLoaders, but this classloader’s loads files from a local file system or a hard drive location. Here are Some of the Use Cases Where we need ClassLoader’s

  1. What if, Some of the Classes in your application is getting used for a finite period of time. How do we do Unloading of classes after a finite period of time? .This way it helps us for better memory management.
  2. Load classes from anywhere Classes can be loaded from anywhere, for example, Database, Networks, or even define it on the fly.

Steps Writing Custom ClassLoaders:-

  1. you need to extend your Custom ClassLoader from java.lang.ClassLoader.
  2. Override the loadClass() method of ClassLoader, this method is responsible for loading our class.
  3. If the Class is already loaded it returns that class
  4. If the class that is requested to load is not present it delegates to parent class loader.
  5. If Parent class loader is not able load the class, then loadClass() calls  findClass()  to find and load class
  6. The class to be loaded must have a public constructor with no arguments.

Custom ClassLoader Example:-

1.Project Structure :-

2. Create a Simple Class:- We create a simple class Frugalis.java, this is the class we load here using our custom ClassLoader.

Frugalis.Java

3. Custom ClassLoader :- We create Our custom ClassLoader which extends ClassLoader and override loadClass() .

4. Running the Example:-

We create a Test.java and create an instance of our MyclassLoader, we load a binary class named as test.frugalis.Frugalis and invoke a method printMyName .

Test.java

Output:-

5. Download Code :-  

This was an example of simple example of Custom ClassLoader. Please add your comments and suggestions .

Related Posts-

  1. Whats are  ClassLoaders and internal working ?

3 Trackbacks / Pingbacks

  1. Spring Boot Profiling - Configure for Different Environments - FrugalisMinds
  2. MVC OR MVVM - Take Your Pick - FrugalisMinds
  3. Top 5 Programming Languages to Learn in 2018 - FrugalisMinds

Leave a Reply

Your email address will not be published.


*