Java: Is there support for macros?

后端 未结 7 1230
暗喜
暗喜 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

    In the case of a Thread, you can pass any object that implements Runnable to its constructor.

    So, the solution is to create your own class:

    public class MyClass implements Runnable {
        void run() {
            // change this line
        }
    }
    

    Unfortunately, run isn't static, so you'll have to create an instance of MyClass first:

    new Thread(new MyClass()).start();
    

    You could also add variables to MyClass and a constructor so you can pass arguments to it.

    Edit: If you need more than just the start method, you can also subclass Thread itself.

提交回复
热议问题