Sujith Shajee
Sujith Shajee

Reputation: 195

How to load a new java file into existing Jar during runtime?

I have a specific requirement where I need to load a class "abc" and invoke a method "xyz" during run time? Is this possible? Should the class file be present in a specific location?

I was trying the below code but am getting a ClassNotFoundException

        File file = new File("location of the class file");
        URL url = file.toURI().toURL();
        URL[] urls = new URL[] {url};

        URLClassLoader myClass = new URLClassLoader(urls);
        Class<?> methodClass = myClass.loadClass("classname");
        Method method = methodClass.getDeclaredMethod(methodname);

Upvotes: 0

Views: 93

Answers (1)

Jernej K
Jernej K

Reputation: 1694

Reflection allows you to create instances and call their methods by specifying the names of class and method. From your description it seems like you want this functionality.

To make it easier to understand. You have the class Reflect:

package com.reflect;

public class Reflect {

  public void testMethod() { System.out.println("Test") }

}

And you have then this main class, where you call this method:

package com.reflect.main;

import java.lang.reflect.Method;

public class ReflectApp {

  public static void main(String[] args) {

    Class noparams[] = {};

    try{
      //load the Reflect at runtime
      Class cls = Class.forName("com.reflect.Reflect");
      Object obj = cls.newInstance();

      //call the testMethod method
      Method method = cls.getDeclaredMethod("testMethod", noparams);
      method.invoke(obj, null);
    } catch(Exception ex) {
      ex.printStackTrace();
    }
  }
}

And here the link again to see the tutorial from where I put my own example.

And in case you have to dynamically load the jar (in case it is not added to the classpath at compile time), you can do that by doing this:

// Getting the jar URL which contains target class
URL[] classLoaderUrls = new URL[]{new URL("file:///home/ashraf/Desktop/simple-bean-1.0.jar")};
URLClassLoader child = new URLClassLoader (classLoaderUrls, this.getClass().getClassLoader());
Class classToLoad = Class.forName ("com.MyClass", true, child);
Method method = classToLoad.getDeclaredMethod ("myMethod");
Object instance = classToLoad.newInstance ();
Object result = method.invoke (instance);

Upvotes: 1

Related Questions