java 通过反射调用main方法
我们可以通过绝对路径让URLClassLoader
,加载一个程序外部的 .class
文件并调用其main
方法
public class Test {
public static void main(String[] args) throws InterruptedException {
Test test = new Test();
test.say();
}
public void say() throws InterruptedException {
int i = 0;
while (true) {
i++;
if (i >= 100) {
break;
}
Thread.sleep(1000);
System.out.println("hello");
}
}
}
package com;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
public class Hello {
public static void main(String[] args)
throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException, MalformedURLException {
File file = new File("../Test.class");
URL[] urls = new URL[1];
urls[0] = file.toURL();
URLClassLoader classLoader = new URLClassLoader(urls);
System.out.println(classLoader);
Class mClass = classLoader.loadClass("Test");
Object test = mClass.newInstance();
Method m1 = mClass.getMethod("main", String[].class);
m1.invoke(null, (Object) new String[] { "a", "b", "c" });
}
}