Tod*_*odd 6 java runtime jar classloader
这是发布在以下问题的延续:如何在运行时加载jar文件
我不确定如何继续方法调用级别.根据我的理解,从clazz对象,我将使用getMethod或getDeclaredMethod来获取一个Method对象,我将从该对象调用invoke.当然,调用需要一个实例.这会是示例代码中所谓的doRun吗?
我是否需要执行doRun.run()方法调用,即使我想执行一个不同于main的方法(假设它是在运行调用调用的doRun对象上的主要方法)?
为了进一步澄清原帖,我问:doRun.run()是否启动了一个新线程来执行clazz类型的类对象的实例?
感谢您帮我解决这个问题.
我确实看过"how-should-i-load-jars-dynamic-at-runtime"(抱歉,只允许一个超链接),但这看起来违反了我引用的第一篇文章中的Class.newInstance邪恶警告.
以下是一些不转换为接口的反射代码:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
将反射类写入消费者代码已知的接口(如示例中所示)通常会更好,因为它允许您避免反射并利用 Java 类型系统。仅当您别无选择时才应使用反射。