Runnable with a parameter?

后端 未结 7 2515
后悔当初
后悔当初 2020-11-27 09:39

I have a need for a \"Runnable that accepts a parameter\" although I know that such runnable doesn\'t really exist.

This may point to fundamental flaw in the design

7条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 10:34

    You could put it in a function.

    String paramStr = "a parameter";
    Runnable myRunnable = createRunnable(paramStr);
    
    private Runnable createRunnable(final String paramStr){
    
        Runnable aRunnable = new Runnable(){
            public void run(){
                someFunc(paramStr);
            }
        };
    
        return aRunnable;
    
    }
    

    (When I used this, my parameter was an integer ID, which I used to make a hashmap of ID --> myRunnables. That way, I can use the hashmap to post/remove different myRunnable objects in a handler.)

提交回复
热议问题