Skip to content

Commit 73a3f2d

Browse files
author
Gary Gregory
committed
Add IORunnable#asRunnable()
1 parent c5e8b7b commit 73a3f2d

2 files changed

Lines changed: 23 additions & 0 deletions

File tree

src/main/java/org/apache/commons/io/function/IORunnable.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
package org.apache.commons.io.function;
1919

2020
import java.io.IOException;
21+
import java.io.UncheckedIOException;
2122

2223
/**
2324
* Like {@link Runnable} but throws {@link IOException}.
@@ -27,6 +28,15 @@
2728
@FunctionalInterface
2829
public interface IORunnable {
2930

31+
/**
32+
* Creates a {@link Runnable} for this instance that throws {@link UncheckedIOException} instead of {@link IOException}.
33+
*
34+
* @return an unchecked Predicate.
35+
*/
36+
default Runnable asRunnable() {
37+
return () -> Uncheck.run(this);
38+
}
39+
3040
/**
3141
* Like {@link Runnable#run()} but throws {@link IOException}.
3242
*

src/test/java/org/apache/commons/io/function/IORunnableTest.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,16 @@
1818
package org.apache.commons.io.function;
1919

2020
import static org.junit.jupiter.api.Assertions.assertEquals;
21+
import static org.junit.jupiter.api.Assertions.assertNull;
22+
import static org.junit.jupiter.api.Assertions.assertThrows;
2123

2224
import java.io.IOException;
25+
import java.io.UncheckedIOException;
26+
import java.nio.file.Files;
27+
import java.util.concurrent.Executors;
2328
import java.util.concurrent.atomic.AtomicReference;
2429

30+
import org.apache.commons.io.file.PathUtils;
2531
import org.junit.jupiter.api.Test;
2632

2733
/**
@@ -42,4 +48,11 @@ public void testAccept() throws IOException {
4248
assertEquals("A1", ref.get());
4349
}
4450

51+
@Test
52+
public void testAsRunnable() throws Exception {
53+
assertThrows(UncheckedIOException.class, () -> Executors.callable(TestConstants.THROWING_IO_RUNNABLE.asRunnable()).call());
54+
final IORunnable runnable = () -> Files.size(PathUtils.current());
55+
assertNull(Executors.callable(runnable.asRunnable()).call());
56+
}
57+
4558
}

0 commit comments

Comments
 (0)