2015-09-07 11:44:36 -06:00
|
|
|
// generics/ThrowGenericException.java
|
2015-12-15 11:47:04 -08:00
|
|
|
// (c)2016 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2015-06-15 17:47:35 -07:00
|
|
|
import java.util.*;
|
|
|
|
|
2016-01-25 18:05:55 -08:00
|
|
|
interface Processor<T, E extends Exception> {
|
2015-06-15 17:47:35 -07:00
|
|
|
void process(List<T> resultCollector) throws E;
|
|
|
|
}
|
|
|
|
|
2016-01-25 18:05:55 -08:00
|
|
|
class ProcessRunner<T, E extends Exception>
|
|
|
|
extends ArrayList<Processor<T, E>> {
|
2015-06-15 17:47:35 -07:00
|
|
|
List<T> processAll() throws E {
|
|
|
|
List<T> resultCollector = new ArrayList<>();
|
2016-01-25 18:05:55 -08:00
|
|
|
for(Processor<T, E> processor : this)
|
2015-06-15 17:47:35 -07:00
|
|
|
processor.process(resultCollector);
|
|
|
|
return resultCollector;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class Failure1 extends Exception {}
|
|
|
|
|
2016-01-25 18:05:55 -08:00
|
|
|
class Processor1 implements Processor<String, Failure1> {
|
2015-06-15 17:47:35 -07:00
|
|
|
static int count = 3;
|
|
|
|
@Override
|
|
|
|
public void
|
|
|
|
process(List<String> resultCollector) throws Failure1 {
|
|
|
|
if(count-- > 1)
|
|
|
|
resultCollector.add("Hep!");
|
|
|
|
else
|
|
|
|
resultCollector.add("Ho!");
|
|
|
|
if(count < 0)
|
|
|
|
throw new Failure1();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class Failure2 extends Exception {}
|
|
|
|
|
2016-01-25 18:05:55 -08:00
|
|
|
class Processor2 implements Processor<Integer, Failure2> {
|
2015-06-15 17:47:35 -07:00
|
|
|
static int count = 2;
|
|
|
|
@Override
|
|
|
|
public void
|
|
|
|
process(List<Integer> resultCollector) throws Failure2 {
|
|
|
|
if(count-- == 0)
|
|
|
|
resultCollector.add(47);
|
|
|
|
else {
|
|
|
|
resultCollector.add(11);
|
|
|
|
}
|
|
|
|
if(count < 0)
|
|
|
|
throw new Failure2();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public class ThrowGenericException {
|
|
|
|
public static void main(String[] args) {
|
2016-01-25 18:05:55 -08:00
|
|
|
ProcessRunner<String, Failure1> runner =
|
2015-06-15 17:47:35 -07:00
|
|
|
new ProcessRunner<>();
|
|
|
|
for(int i = 0; i < 3; i++)
|
|
|
|
runner.add(new Processor1());
|
|
|
|
try {
|
|
|
|
System.out.println(runner.processAll());
|
|
|
|
} catch(Failure1 e) {
|
|
|
|
System.out.println(e);
|
|
|
|
}
|
|
|
|
|
2016-01-25 18:05:55 -08:00
|
|
|
ProcessRunner<Integer, Failure2> runner2 =
|
2015-06-15 17:47:35 -07:00
|
|
|
new ProcessRunner<>();
|
|
|
|
for(int i = 0; i < 3; i++)
|
|
|
|
runner2.add(new Processor2());
|
|
|
|
try {
|
|
|
|
System.out.println(runner2.processAll());
|
|
|
|
} catch(Failure2 e) {
|
|
|
|
System.out.println(e);
|
|
|
|
}
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
[Hep!, Hep!, Ho!]
|
|
|
|
Failure2
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|