编译成功后打印消息

Print Message after successfully compilation

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

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

或者如果你想做问题标题中的事情并在构建之后做一些事情,那么你可以考虑一个构建自动化工具,比如Maven

尽管以下代码片段对于您的任务而言过于复杂,但是,扩展我的评论 - 您可能希望将自定义任务提交给 class 它实现了 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);