Java使用反射调用类的main()方法 [英] Java call main() method of a class using reflection

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

问题描述

我需要使用反射从另一个主方法调用Java类的main方法。

I need to call the main method of a Java class from another main method using reflection.

反射的使用是必须的,以便删除编译时依赖性被称为主要类。
简单直接的方法不会产生,因为它只识别'公共'和'非静态'方法。
建议?

Usage of reflection is a must so as to remove compile time dependency of the main class being called. Straightforward approach is not yielding as it recognizes only 'public' and 'non-static' method. Suggestions?

推荐答案

不应该比调用任何其他函数更复杂:

Shouldn't be any more complicated than calling any other function:

public static void main(String[] args) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    Class<?> cls = Class.forName("pkg1.pkg2.classname");
    Method meth = cls.getMethod("main", String[].class);
    String[] params = null; // init params accordingly
    meth.invoke(null, (Object) params); // static method doesn't have an instance
}

但我不是真的看到它的许多用途,它唯一能给你买的就是你可以编译程序而不用连接另一个程序,只要你从不使用那个特定的代码路径,但如果这就是你需要的,我们就去;)

But I don't really see many uses for that, the only thing it buys you is that you can compile the program without linking the other one as long as you never use that specific code path, but if that's what you need, here we go ;)

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

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