设计了java的main函数的前置钩子

package top.dreamcenter.core;

import java.util.InputMismatchException;

class MyException extends Exception{
    private static final long serialVersionUID = 1L;
    @Override
    public String getMessage() {
        return "************my-exception!";
    }
}

public class CoreTest extends Thread{
    
    private static String[] myArgs;
    private static boolean start = false;
    
    static {
        print("before");
        myArgs = null;
        new CoreTest().start();
    }
    
    public static void main(String[] args) throws MyException {
        if(!start && args.length != 0) {
            print("main-before[with args]");
            print("args/" + args[0]);
            myArgs = args;
            print("args/" + myArgs[0]);
            start = true;
        } else if(!start && args.length == 0){
            print("main-before[with no args]");
            start = true;
        } else {
            /*
             *这里和往常一样写main函数就可以了 
             */
            print("main-realrun");
            System.out.println(args[0]);
            throw new MyException();
        }
    }

    private static void print(String str) {
        StackTraceElement temp=Thread.currentThread().getStackTrace()[2];
        System.err.printf("%-20s","debug : " + temp.getMethodName());
        System.err.println("-" + str);
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("ready to run ...");
        while(!start) {
            yield();            
        }
        System.out.println("run");
        try {
            main(myArgs);
        }catch(MyException e) {
            System.out.println(e.getMessage());
        }
    }
}

独创,转发表明就好😂

posted @ 2021-07-17 21:25  时光潜流  阅读(84)  评论(0编辑  收藏  举报