如何在运行时从外部jar访问方法? [英] How does one access a method from an external jar at runtime?

查看:188
本文介绍了如何在运行时从外部jar访问方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是以下问题的延续:如何加载运行时的jar文件

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

我不确定如何继续方法调用级别。根据我的理解,来自clazz对象的
,我会使用getMethod或getDeclaredMethod来获取一个我将调用invoke的Method对象。当然,调用需要一个实例。这会是示例代码中所谓的doRun吗?

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?

我是否需要执行doRun.run()方法调用,即使我想执行不同的方法比main(假设它是运行调用调用的doRun对象的主要部分)?

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)?

为了进一步澄清原帖,我问:
doRun.run()是否启动了执行类对象实例的新线程clazz?

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-load-jars-dynamic-at-runtime(对不起,只允许一个超链接),但这看起来违反了我引用的第一篇文章中的Class.newInstance邪恶警告。

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.

推荐答案

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

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.

这篇关于如何在运行时从外部jar访问方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆