Java: Is there support for macros?

后端 未结 7 1190
暗喜
暗喜 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:27

    One technique is to put the code in an anonymous inner class, and pass that to a method that does the rest.

    interface SomeInterface {
        void fn();
    }
    
        executeTask(new SomeInterface {
            public void fn() {
                // Change this line.
            }
        });
    
    private void executeTask(final SomeInterface thing) {
         Thread thread = new Thread(new Runnable() { public void run() {
            //...
            //...
            //...
            thing.fn();
            //...
            //...
         }});
         thread.start();
    }
    

    Generally it isn't a good idea to extend Thread or other classes if it is unnecessary.

提交回复
热议问题