How does one access a method from an external jar at runtime?

前端 未结 3 619
刺人心
刺人心 2021-01-12 15:51

This is a continuation of the question posted in: How to load a jar file at runtime

I am uncertain as to how to continue to the method invocation level. From my und

3条回答
  •  暖寄归人
    2021-01-12 16:09

    Sample Program:

    Project Printer:

    public class Printer {
    
        public void display(String printtext)
        {
            System.out.println(printtext);
        }
    
    }
    

    This project is exported as Printer.jar.

    Printer Class has method display() which takes string as input.

    Invoking code:

           URL url = new URL("file:Printer.jar"); 
           URLClassLoader loader = new URLClassLoader (new URL[] {url});
           Class cl = Class.forName ("Printer", true, loader);
           String printString = "Print this";
           Method printit = cl.getMethod("display", String.class);
           Constructor ctor = cl.getConstructor(); //One has to pass arguments if constructor takes input arguments.
           Object instance = ctor.newInstance();
           printit.invoke(instance, printString);
           loader.close ();
    

    Output: Print this

提交回复
热议问题