如何在java中使用反射调用类的main()方法 [英] How to call main() method of a class using reflection in java

查看:152
本文介绍了如何在java中使用反射调用类的main()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用反射从另一个main方法调用Java类的main方法时,

When calling the main method of a Java class from another main method using reflection,

Class thisClass = loader.loadClass(packClassName);
Method thisMethod = thisClass.getDeclaredMethod("main",String[].class);

thisMethod.invoke(null, new String[0]);

我应该创建newInstance()还是简单地调用main(),因为它是静态的。

Should i create newInstance() or simply call main() as it is static.

推荐答案

对于你声明的要求(动态调用随机类的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();
}

这篇关于如何在java中使用反射调用类的main()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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