Java call main() method of a class using reflection

后端 未结 2 1172
鱼传尺愫
鱼传尺愫 2021-02-02 12:02

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 ma

相关标签:
2条回答
  • 2021-02-02 12:15

    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 ;)

    0 讨论(0)
  • 2021-02-02 12:27

    If you have 2 java files that both have the main method, can't you compile them as different projects and call one from the other?

    0 讨论(0)
提交回复
热议问题