Java教程

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

本文主要是介绍设计了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());
        }
    }
}

独创,转发表明就好

这篇关于设计了java的main函数的前置钩子的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!