OnJava8-Examples/generics/ThrowGenericException.java

75 lines
1.8 KiB
Java
Raw Normal View History

2015-04-20 15:36:01 -07:00
//: generics/ThrowGenericException.java
2015-05-29 14:18:51 -07:00
// <20>2015 MindView LLC: see Copyright.txt
2015-04-20 15:36:01 -07:00
import java.util.*;
interface Processor<T,E extends Exception> {
void process(List<T> resultCollector) throws E;
}
class ProcessRunner<T,E extends Exception>
extends ArrayList<Processor<T,E>> {
List<T> processAll() throws E {
2015-05-05 11:20:13 -07:00
List<T> resultCollector = new ArrayList<>();
2015-04-20 15:36:01 -07:00
for(Processor<T,E> processor : this)
processor.process(resultCollector);
return resultCollector;
}
2015-05-18 23:05:20 -07:00
}
2015-04-20 15:36:01 -07:00
class Failure1 extends Exception {}
class Processor1 implements Processor<String,Failure1> {
static int count = 3;
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
public void
process(List<String> resultCollector) throws Failure1 {
if(count-- > 1)
resultCollector.add("Hep!");
else
resultCollector.add("Ho!");
if(count < 0)
throw new Failure1();
}
2015-05-18 23:05:20 -07:00
}
2015-04-20 15:36:01 -07:00
class Failure2 extends Exception {}
class Processor2 implements Processor<Integer,Failure2> {
static int count = 2;
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
public void
process(List<Integer> resultCollector) throws Failure2 {
if(count-- == 0)
resultCollector.add(47);
else {
resultCollector.add(11);
}
if(count < 0)
throw new Failure2();
}
2015-05-18 23:05:20 -07:00
}
2015-04-20 15:36:01 -07:00
public class ThrowGenericException {
public static void main(String[] args) {
ProcessRunner<String,Failure1> runner =
2015-05-05 11:20:13 -07:00
new ProcessRunner<>();
2015-04-20 15:36:01 -07:00
for(int i = 0; i < 3; i++)
runner.add(new Processor1());
try {
System.out.println(runner.processAll());
} catch(Failure1 e) {
System.out.println(e);
}
ProcessRunner<Integer,Failure2> runner2 =
2015-05-05 11:20:13 -07:00
new ProcessRunner<>();
2015-04-20 15:36:01 -07:00
for(int i = 0; i < 3; i++)
runner2.add(new Processor2());
try {
System.out.println(runner2.processAll());
} catch(Failure2 e) {
System.out.println(e);
}
}
} ///:~