Kas*_*der 5 java generics lambda java-8
我面临一些lambda问题.
我正在尝试使用lambda表达式和函数接口来创建接受函数接口和一些参数并执行该函数的方法.
这是我的代码:
@FunctionalInterface
interface TwoArgumentFunction {
public <T, K, V> T doJob(K arg1, V arg2);
} //I know I've ommited return value in that case
class SomeClass {
<T, K, V> T runLongAction(TwoArgumentFunction action, K arg1, V arg2){
SwingWorker<T, Void> worker = new SwingWorker<T, Void>(){
@Override
protected T doInBackground() throws Exception {
{... some code ... }
return action.doJob(arg1, arg2);
}
@Override
protected void done(){
{... some code ... }
}
};
worker.execute();
try {
return worker.get();
} catch (InterruptedException | ExecutionException e) {
{... some code ... }
}
}
void mainInvoke(ArgType1 arg1, ArgType2 arg2){
runLongAction((arg1, arg2) -> doSomething(arg1, arg2), arg1, arg2);
}
Run Code Online (Sandbox Code Playgroud)
}
我有错误:
对于SomeClass类型,方法runLongAction((arg1,arg2) - > {},ArgType1,ArgType2)是未定义的
我甚至尝试将lambda转换为TwoArgumentFunction,但后来我得到了:
非法lambda表达式:TwoArgumentFunction类型的方法doJob是通用的
Anonymouse类而不是lambda表达式工作正常,这是我发现的最简单的解决方法.
试试看:
@FunctionalInterface
interface TwoArgumentFunction<T, K, V> {
T doJob(K arg1, V arg2);
} //I know I've ommited return value in that case
public <T, K, V> T runLongAction(final TwoArgumentFunction<? extends T, ? super K, ? super V> action, final K arg1, final V arg2) {
return action.doJob(arg1, arg2);
}
private void test() {
final String a = "A";
final Long b = 1L;
this.runLongAction((ta, tb) -> {return 1;}, a, b);
}
Run Code Online (Sandbox Code Playgroud)
你把泛型放在方法上,而我把它放在界面上.而且我还添加? super和? extends(但这项工作没有它).
如果你不知道它并且你需要它,你也可以将类型放在lambda中:
this.runLongAction((String ta, Long tb) -> {return 1;}, a, b);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8275 次 |
| 最近记录: |