【问题标题】:Print Message after successfully compilation编译成功后打印消息
【发布时间】:2015-09-17 05:18:27
【问题描述】:

我有一个简单的 JAVA 代码,它只会在编译和运行程序后打印 hello。但我想在成功完成后打印一条消息。这可能吗?如果是,比如何?

【问题讨论】:

  • 您必须深入了解进程父/子退出事件

标签: java compile-time


【解决方案1】:

虽然,以下代码 sn-p 对于您的任务来说太过分了,但是,扩展我的评论 - 您可能希望将自定义任务提交给类 它实现了Callable

public class Main {
    public static void main(String[] args) {
        final ExecutorService executorService;
        final Future<Integer> future;
        final int statusCode;

        executorService = Executors.newFixedThreadPool(1);
        future = executorService.submit(new TextMessagePrinter());

        try {
            statusCode = future.get();
            if (statusCode == 10) { // Printed successfully
                System.out.println("JOB DONE. EXITING...");
                Runtime.getRuntime().exit(0); // A zero status code indicates normal termination.
            } else {
                System.out.println("ERR...SOMETHING WEIRD HAPPENED!");
                Runtime.getRuntime().exit(statusCode);  // A non-zero status code indicates abnormal termination.
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } finally {
            executorService.shutdownNow();
        }
    }
}

class TextMessagePrinter implements Callable<Integer> {
    public Integer call() {
        Integer STATUS_CODE;
        try {
            System.out.println("Printing hello..."); // Try printing something
            System.out.println("Dividing 6 by 0 gives us: " + 6 / 0); // And then you try to do something knowing which will result in an exception
            STATUS_CODE = 10; // Indicates success.
        } catch (ArithmeticException e) {
            STATUS_CODE = 20; // Indicates failure...setting status code to 20.
        }
        return STATUS_CODE;
    }
}

在我的 IDE 上运行上述代码会得到以下输出:

  • 异常发生时

(注意状态码设置在 catch 块中在进程完成时打印出来):

  • 没有异常,一切正常:

(评论下一行)

System.out.println("Dividing 6 by 0 gives us: " + 6 / 0);

【讨论】:

    【解决方案2】:

    如果您的意思是完成应用程序的运行时,我认为您正在以下 StackOverflow 问题中寻找答案:Java Runtime Shutdown Hook

    或者,如果您想在构建后执行问题标题中的内容并执行某些操作,那么您可以考虑构建自动化工具,例如 Maven

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-05
      • 1970-01-01
      • 1970-01-01
      • 2016-12-18
      • 1970-01-01
      相关资源
      最近更新 更多