在Java中是否可以调用另一个类的main方法并返回到调用代码? [英] Is it possible in Java to Invoke another class' main method and return to the invoking code?

查看:180
本文介绍了在Java中是否可以调用另一个类的main方法并返回到调用代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class A{
    public static void main(String[] args)
    {
        //Main code
    }
}

public class B{
    void someMethod()
    {
        String[] args={};
        A.main();
        System.out.println("Back to someMethod()");
    }
}



有什么办法吗?去做这个?我找到了一种使用反射做同样的方法,但也没有返回到调用代码。我尝试使用 ProcessBuilder 在一个单独的进程中执行它,但我想我错过了一些东西。


Is there any way to do this? I found a method of doing the same using reflection but that doesn't return to the invoking code either. I tried using ProcessBuilder to execute it in a separate process but I guess I was missing out something.

推荐答案

你的代码已经差不多了 - 它只是没有传入参数:

Your code already nearly does it - it's just not passing in the arguments:

String[] args = {};
A.main(args);

main 方法只是特殊就它被视为切入点而言。它是一种非常普通的方法,可以从其他代码中调用而没有任何问题。当然,如果它以期望的方式编写,它可能会遇到问题,它只被称为入口点(例如,如果它使用 System.exit )但从语言的角度来看,这很好。

The main method is only "special" in terms of it being treated as an entry point. It's otherwise a perfectly normal method which can be called from other code with no problems. Of course you may run into problems if it's written in a way which expects it only to be called as an entry point (e.g. if it uses System.exit) but from a language perspective it's fine.

这篇关于在Java中是否可以调用另一个类的main方法并返回到调用代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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