[英]How to call main() method of a class using reflection in java
When calling the main method of a Java class from another main method using reflection, 当使用反射从另一个main方法调用Java类的main方法时,
Class thisClass = loader.loadClass(packClassName);
Method thisMethod = thisClass.getDeclaredMethod("main",String[].class);
thisMethod.invoke(null, new String[0]);
Should i create newInstance() or simply call main() as it is static. 我应该创建newInstance()还是简单地调用main(),因为它是静态的。
For your stated requirements (dynamically invoke the main method of a random class, with reflection you have alot of unnecessary code. 对于您声明的要求(动态调用随机类的主要方法,使用反射,您有很多不必要的代码。
You can adapt the following code to meet your needs: 您可以调整以下代码以满足您的需求:
try {
final Class<?> clazz = Class.forName("blue.RandomClass");
final Method method = clazz.getMethod("main", String[].class);
final Object[] args = new Object[1];
args[0] = new String[] { "1", "2"};
method.invoke(null, args);
} catch (final Exception e) {
e.printStackTrace();
}
Perceptions answer looks correct; 认知答案看起来是正确的; if you need load from a Jar not in the class path you can use a URL class loader
如果您需要从不在类路径中的Jar加载,则可以使用URL类加载器
try {
URL[] urls;
URLClassLoader urlLoader;
urls = ...;
urlLoader = new URLClassLoader(urls);
@SuppressWarnings("rawtypes")
Class runClass = urlLoader.loadClass(classToRun);
Object[] arguments = new Object[]{args};
Method mainMethod = runClass.getMethod("main", String[].class);
mainMethod.invoke(null, arguments);
} catch (Exception e) {
e.printStackTrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.