简体   繁体   中英

Java call main() method of a class using reflection

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

如果你有两个都有main方法的java文件,你不能把它们编译为不同的项目并从另一个项目调用吗?

Method mainMethod = clazz.getDeclaredMethod("main", String[].class);
final Object[] args = new Object[1];
args[0] = new String[]{"1", "2"};
mainMethod.invoke(null, args);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM