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

前端 未结 3 617
刺人心
刺人心 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:13

    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.

提交回复
热议问题