Search code examples
javajarruntimeclassloader

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


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 understanding, from the clazz object, I would used getMethod or getDeclaredMethod to get a Method object from which I would call invoke. Of course, invoke requires an instance. Would that then be what is called doRun in the example code?

Do I need to perform the doRun.run() method call even though I want to execute a different method than main (assuming that it is main on the doRun object that is called with the run invocation)?

Just for more clarification of the original post, I ask: Does doRun.run() start a new thread executing the instance of the class object of type clazz?

Thanks for helping to clear this up for me.

I did look at "how-should-i-load-jars-dynamically-at-runtime" (sorry, only allowed one hyperlink), however this looked to violate the Class.newInstance evilness admonition in the first post I referenced.


Solution

  • Here is some reflection code that doesn't cast to an interface:

    public class ReflectionDemo {
    
      public void print(String str, int value) {
        System.out.println(str);
        System.out.println(value);
      }
    
      public static int getNumber() { return 42; }
    
      public static void main(String[] args) throws Exception {
        Class<?> clazz = ReflectionDemo.class;
        // static call
        Method getNumber = clazz.getMethod("getNumber");
        int i = (Integer) getNumber.invoke(null /* static */);
        // instance call
        Constructor<?> ctor = clazz.getConstructor();
        Object instance = ctor.newInstance();
        Method print = clazz.getMethod("print", String.class, Integer.TYPE);
        print.invoke(instance, "Hello, World!", i);
      }
    }
    

    Writing the reflected classes to an interface known by the consumer code (as in the example) is generally better because it allows you to avoid reflection and take advantage of the Java type system. Reflection should only be used when you have no choice.