user3736174
user3736174

Reputation: 383

How to invoke a Java class of another Jar file?

I would like to receive the results dynamically invoke a class in another jar.

For example,

'A' directory in a file named A.jar.

'B' directory in a file named B.jar.

I want to dynamically invoke a class of A.jar file to B.jar file.

This is the main class of A.jar file.

Socket and RMI are not considered because the message exchange technology.

Main Class (B.jar)

public class main {
public static void main(String[] args) {
    //It dynamically creates an object of a Message Class in A.jar.
    //And it invoke the getMessage function.
    //And Save the return value.

}}

Message Class (A.jar)

public class message{
    public String getMessage(){ 

       return "Hello!";
    }
}

Upvotes: 4

Views: 10383

Answers (1)

Andreas Fester
Andreas Fester

Reputation: 36630

First, you need to dynamically create an instance of the given class:

Class<?> clazz = Class.forName("message");
Object messageObj = clazz.newInstance();

This assumes that the .jar file which contains the message class is on the classpath so that the Java runtime is able to find it. Otherwise, you need to manually load the jar file through a class loader, e.g. like in How should I load Jars dynamically at runtime?. Assumed that your A.jar file which contains the message class is located at c:\temp\A.jar, you can use something like

URLClassLoader child = new URLClassLoader (
        new URL[] {new URL("file:///c:/temp/A.jar")}, main.class.getClassLoader());
Class<?> clazz = Class.forName("message", true, child);

to load the jar file and load the message class from it.

In both cases, you can then retrieve the method from the class and invoke it on the created instance:

Method getMessage = clazz.getMethod("getMessage");
String result = (String) getMessage.invoke(messageObj);

Upvotes: 9

Related Questions