且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在java中使用反射调用类的main()方法

更新时间:2022-06-23 03:08:11

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