成功编译后打印消息

时间:2015-09-17 05:18:27

标签: java compile-time

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

2 个答案:

答案 0 :(得分:1)

虽然,以下代码片段对您的任务来说太过分了,但是,扩展我的评论 - 您可能想要向类提交自定义任务 它实现了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块中设置的状态代码会被打印):

enter image description here

  • 没有异常发生,一切都很好:

(评论以下一行)

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

enter image description here

答案 1 :(得分:0)

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

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