Search code examples
javajarexecute

Invoke and pass parameters and get the return value of certain method defined in separate jar file


Assume that I have a .jar file A which has method "long calculateSomething(String args)". A.jar is stored in folder /service. Now, I want to develop a java application which can invoke method calculateSomething from A.jar file, execute and get the return value from this method. How can I achieve it?

Oracle has a similar example in following link:

http://docs.oracle.com/javase/tutorial/deployment/jar/apiindex.html

However, It call and execute the main method in A.jar file with void return. Hence, I could not apply that technique. Could you please tell me the solution for my problem?

Thank you


Solution

  • For your program to be able to use a class of foo.jar, foo.jar must be in the classpath, that's all.

    So you'll have to compile your code with

    javac -cp foo.jar ...
    

    and to run your code with

    java -cp foo.jar:/the/folder/where/your/classes/are ...
    

    or

    java -cp foo.jar;c:\the\folder\where\your\classes\are ...
    

    if you're on Windows.

    The Java code itself is exactly the same as if the class you want to use was one of your own classes, rather than a class in foo.jar.