Java: Is there support for macros?

后端 未结 7 1207
暗喜
暗喜 2021-02-12 17:47

I am just curious on how people solve this. I often write the same type of code all the time. For instance:

new Thread() {
   //...
   //...
   //...
   //Change         


        
7条回答
  •  名媛妹妹
    2021-02-12 18:28

    You can use the template pattern to create a base class that contains the common code. For example:

    public abstract class ThreadTemplate extends Thread
    {
    
        public void run() {
            //reusable stuff
            doInThread();
            //more resusable stuff
        }
    
        abstract void doInThread();
    
    }
    

    Then starting a thread with the boilerplate code is as easy as:

    new ThreadTemplate{
       void doInThread() {
           // do something
       }
    }.start();
    

    Also, a less elegant solution to save yourself some typing is to use the templating feature of your ide. You can find some info on setting them up in Eclipse here and you can find a list of useful ones at Useful Eclipse Java Code Templates

提交回复
热议问题