我需要一个“接受参数的可运行对象”,尽管我知道这样的可运行对象实际上并不存在。

这可能是我的应用程序设计中的根本缺陷,或者是我疲惫的大脑中的心理障碍,所以我希望在这里找到一些关于如何在不违反基本OO原则的情况下完成以下内容的建议:

  private Runnable mOneShotTask = new Runnable(String str) {
    public void run(String str) {
       someFunc(str);
    }
  };  

你知道如何完成上面的事情吗?


当前回答

目前为止最好的方法:

Consumer<String> oneShot = str -> {
    
   somefunc(str);
    
};

oneShot.accept("myString");

其他回答

我首先想知道你在这里要完成什么,需要一个参数传递给new Runnable()或run()。 通常的方法应该是有一个Runnable对象,它通过在启动前设置成员变量将数据(str)传递给它的线程。run()方法然后使用这些成员变量值执行someFunc()

你可以把它放到一个函数里。

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;

}

(当我使用这个时,我的参数是一个整数ID,我用它来创建ID的hashmap——> myRunnables。这样,我可以使用hashmap在处理程序中发布/删除不同的myRunnable对象。)

从Java 8开始,最好的答案是使用Consumer<T>:

https://docs.oracle.com/javase/8/docs/api/java/util/function/Consumer.html

它是函数接口之一,这意味着你可以将它作为lambda表达式调用:

void doSomething(Consumer<String> something) {
    something.accept("hello!");
}

...

doSomething( (something) -> System.out.println(something) )

...
/**
 * @author AbdelWadoud Rasmi
 * <p>
 * The goal of this class is to pass some parameters to a runnable instance, a good example is
 * after caching a file you need to pass the new path to user to do some work on it.
 */
public abstract class ParameterizedRunnable implements Runnable {
    private Object[] params;

    /**
     * @param params: parameters you want to pass the the runnable.
     */
    public ParameterizedRunnable(Object... params) {
        this.params = params;
    }

    /**
     * Code you want to run
     *
     * @param params:parameters you want to pass the the runnable.
     */
    protected abstract void run(Object... params);

    @Override
    public final void run() {
        run(params);
    }

    /**
     * setting params
     */
    public void setParams(Object... params) {
        this.params = params;
    }

    /**
     * getting params
     */
    public Object[] getParams() {
        return params;
    }
}

目前为止最好的方法:

Consumer<String> oneShot = str -> {
    
   somefunc(str);
    
};

oneShot.accept("myString");