所以我连续20个二传手,所有这些都可能会失败.如果一个失败或者用try catch包围它们而不是跳过它们,那么有没有办法用Java 8s的一些功能做到这一点?
例如,我在想这样的事情:
public void mapElement(Function function) {
try the function
catch if something goes wrong
}
Run Code Online (Sandbox Code Playgroud)
然后我可以像这样使用它:
mapElement(myObject.putA(a));
mapElement(myObject.putB(b));
mapElement(myObject.putC(c));
....
Run Code Online (Sandbox Code Playgroud)
shm*_*sel 10
这样的事情怎么样:
public void tryTo(Runnable action) {
try {
action.run();
} catch (Exception e) {
// do something?
}
}
tryTo(() -> myObject.putA(a));
tryTo(() -> myObject.putB(b));
tryTo(() -> myObject.putC(c));
Run Code Online (Sandbox Code Playgroud)
需要注意的是myObject,a,b并且c都需要是有效最终这个工作.
上面的一个旋转是有一个方法,它接受一个Runnables 数组并在循环中执行它们:
public void tryAll(Runnable... actions) {
for (Runnable action : actions) {
try {
action.run();
} catch (Exception e) {
// do something?
}
}
}
tryAll(() -> myObject.putA(a),
() -> myObject.putB(b),
() -> myObject.putC(c));
Run Code Online (Sandbox Code Playgroud)
您可以使用Runnable功能界面.
它的函数描述符是() -> void.
它完全适合您的需要,因为映射操作不返回任何结果,您也不需要指定任何参数作为函数的输入.
确实在这里:myObject.putA(a),你不想将a参数传递给函数.
你想要将整个表达式myObject.putA(a)作为lambda体传递:
() -> myObject.putA(a);
你可以写这个mapElement()方法:
public static void mapElement(Runnable mapProcessor) {
// Retry logic
try {
mapProcessor.run();
} catch (Exception e) {
// exception handling
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,要捕获任何Java异常(已检查和运行时),您必须捕获RuntimeException而不是Exception.
你可以这样使用mapElement():
MyObject myObject = new MyObject();
...
mapElement(() -> myObject.putA(a));
mapElement(() -> myObject.putB(b));
mapElement(() -> myObject.putC(c));
Run Code Online (Sandbox Code Playgroud)
Runnable可能无法传达预期的含义,因为它主要是为线程执行而设计的.
如果有意义,您也可以介绍自己的功能界面.
通过这种方式,如果它看起来相关,您也可以在函数中声明任何特定的已检查异常.
这是不可能的Runnable.
例如 :
@FunctionalInterface
public interface MapProcessor{
void map() throws MappingException;
}
Run Code Online (Sandbox Code Playgroud)
您可以这样使用它:
public static void mapElement(MapProcessor mapProcessor) {
// Retry logic
try {
mapProcessor.map();
}
catch (MappingException e) {
// Mapping exception handling
}
catch (Exception e) { // or RuntimeException if more relevant
// other exception handling
}
}
Run Code Online (Sandbox Code Playgroud)