Monday, 10 June 2019

Java: Load a class using URLClassLoader


In this post, I am going to explain how to load a class using URLClassLoader.
a.   Create a jar file
b.   Load the class from jar file using URLClassLoader.

Create a jar file
Create Employee.java file and follow below directory structure.

$tree
.
└── com
    └── sample
        └── demoapp
            └── model
                └── Employee.java


Employee.java
package com.sample.demoapp.model;

public class Employee {

 public String toString() {
  return "Represent Employee Information";
 }
}


Compile Employee.java.
$javac com/sample/demoapp/model/Employee.java 
$
$tree
.
└── com
    └── sample
        └── demoapp
            └── model
                ├── Employee.class
                └── Employee.java

Create ‘demoapp.jar’ file by executing below command.

jar -cvf demoapp.jar *

$jar -cvf demoapp.jar *
added manifest
adding: com/(in = 0) (out= 0)(stored 0%)
adding: com/sample/(in = 0) (out= 0)(stored 0%)
adding: com/sample/demoapp/(in = 0) (out= 0)(stored 0%)
adding: com/sample/demoapp/model/(in = 0) (out= 0)(stored 0%)
adding: com/sample/demoapp/model/Employee.class(in = 326) (out= 244)(deflated 25%)
adding: com/sample/demoapp/model/Employee.java(in = 137) (out= 112)(deflated 18%)
$
$tree
.
├── com
│   └── sample
│       └── demoapp
│           └── model
│               ├── Employee.class
│               └── Employee.java
└── demoapp.jar

Step 2: Load the class using URLClassLoader.
URL url = new URL("file:/Users/krishna/Documents/demoapp.jar");
URLClassLoader classLoader = new URLClassLoader(new URL[] {url});
Class clazz = classLoader.loadClass("com.sample.demoapp.model.Employee");

Step 3: Once the class is loaded, you can create an instance to the class Employee and use.
Object obj = clazz.newInstance();


App.java
package com.sample.app;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class App {

 public static void main(String args[]) throws MalformedURLException, ClassNotFoundException, InstantiationException, IllegalAccessException {
  URL url = new URL("file:/Users/krishna/Documents/TechnicalDocuments/Java/examples/classloading/demoapp.jar");

  URLClassLoader classLoader = new URLClassLoader(new URL[] {url});
  Class clazz = classLoader.loadClass("com.sample.demoapp.model.Employee");

  Object obj = clazz.newInstance();
  
  System.out.println(obj);
 }
}

Run App.java, you can able to see below messages in console.

Represent Employee Information


Previous                                                 Next                                                 Home

No comments:

Post a Comment