且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在运行时从外部jar访问方法?

更新时间:2023-09-29 22:32:46

以下是一些不会转换为接口的反射代码:

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);
  }
}

将反映的类写入消费者已知的接口代码(在示例中)是通常更好,因为它允许您避免反射并利用Java类型系统。只有在你别无选择时才能使用反思。

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.