下面的结构是如何工作的? 请解释一下。
提前致谢。
public abstract class AbstractCallableClass {
protected abstract V getCallable();
public void passRunnable() {
runnableParamterised(this.getCallable());
}
public void runnableParamterised(Runnable runnable) {
System.out.println(runnable.toString());
}
}
class OneCallableClass implements Callable {
@Override
public Object call() throws Exception {
return "Any dummy response";
}
}
class TestClass extends AbstractCallableClass {
@Override
protected V getCallable() {
return new OneCallableClass();
}
}
它没有像上面示例中提到的那样工作。但显然,当作为参数传递并在生产环境中运行时,Callable 会被类型转换为 Runnable。
您不能将
Callable
转换为 Runnable
- 它将导致 ClassCastException
,除非可调用对象也是可运行对象(想象一个实现两个接口的类)。
您可以实现一个简单的适配器来包装可调用对象,以将其作为可运行对象传递(如果需要):
public class RunnableAdapter implements Runnable {
private final Callable<?> callable;
public RunnableAdapter(Callable<?> callable) {
this.callable = callable;
}
@Override
public void run() {
try {
callable.call();
} catch (Exception exc) {
throw new RuntimeException(exc);
}
}
}
用途:
runnableParamterised(new RunnableAdapter(callable));