3

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!";
    }
}
user3736174
  • 333
  • 2
  • 3
  • 16

1 Answers1

9

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);
Community
  • 1
  • 1
Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
  • Thank you for answer. How can i invoke a class in another jar file? – user3736174 Dec 10 '15 at 08:59
  • As long as the other jar file is on the classpath, the above approach works. Otherwise, you need to dynamically load the jar file at runtime through a class loader. – Andreas Fester Dec 10 '15 at 09:04
  • I'm not sure how to approach the given answer. where can i find a good pratical example. – user3736174 Dec 10 '15 at 09:07
  • I am still not clear about your actual issue - is your `A.jar` file on your classpath or not? If so, you can instantiate any public class from `A.jar` through `Class.forName`. Otherwise, you need to load `A.jar` through a class loader. – Andreas Fester Dec 10 '15 at 09:11
  • What I want, I want to dynamically invoke the another jar file, regardless of the classpath. – user3736174 Dec 10 '15 at 09:22
  • See my updated answer. To be pedantic, you can not invoke a jar file - you can only invoke methods from classes contained in a jar file. – Andreas Fester Dec 15 '15 at 12:55