java对异常泛型的简单实例
2012-02-27 23:25
393 查看
因为泛型具有擦除的特性,所以在现在的java中不支持try{}catch{}的catch子句中不支持对泛型的使用,为了使写的代码在异常的处理方面具有更好的泛型特性,需要在声明类的时候让泛型继承自Exception或者是Throwable,这样在对象进行实例化的时候便可以指定具体的异常类型,下面是异常泛型的小例子
/** * Because of erasure, the use of generics with exceptions is extremely limited. * A catch clause cannot catch an exception of a generic type, because the exact * type of the exception must be known at both compile time and run time. Also, * a generic class can’t directly or indirectly inherit from Throwable (this * further prevents you from tryi ng to define generic exceptions that can’t be * caught). However, type parameters may be used in the throws clause of a * method declaration. This allows you to write generic code that varies with * the type of a checked exception * * @author Eric * */ public class ExceptionOfGeneric { public static void main(String args[]) { ProcessRunner<String, Process1Exception> pr1 = new ProcessRunner<String, Process1Exception>(); pr1.add(new ProcessImp1()); try { System.out.println(pr1.runnAlllProcess()); } catch (Process1Exception e) { e.printStackTrace(); } ProcessRunner<Integer, Process2Exception> pr2 = new ProcessRunner<Integer, Process2Exception>(); pr2.add(new ProcessImp2()); try { System.out.println(pr2.runnAlllProcess()); } catch (Process2Exception e) { e.printStackTrace(); } } } interface Process<T, E extends Exception> { public void process(List<T> t) throws E; } class Process1Exception extends Exception {} class Process2Exception extends Exception {} class ProcessRunner<T, E extends Exception> extends ArrayList<Process<T, E>> { List<T> runnAlllProcess() throws E { List<T> results = new ArrayList<T>(); for (Process<T, E> t : this) { // execute process may be throw variable type of exception t.process(results); } return results; } } class ProcessImp1 implements Process<String, Process1Exception> { public void process(List<String> strs) throws Process1Exception { strs.add("HELLO"); } } class ProcessImp2 implements Process<Integer, Process2Exception> { public void process(List<Integer> t) throws Process2Exception { t.add(10); } }
相关文章推荐
- 简单实例解读Java泛型
- 从简单实例看JAVA的异常处理机制。
- java异常处理的简单实例和解释,自定义一个异常类
- JAVA内存异常简单实例
- java 泛型总结 简单实例
- java语言搭建SSL的Socket并发送字符串消息(最简单应用实例/常见异常及解决)
- java 实现第二个实例实现Bank ,进行简单的注册,简单的异常的分析!
- Java中的泛型方法详解及简单实例
- JAVA超级简单的爬虫实例讲解
- java一个简单的自定义异常工具类
- Java的泛型之简单讲解
- Java WebService 简单实例
- java连接oracle的简单实例
- Java语言引入泛型的好处是安全简单
- Java day08 异常实例 上课时电脑出问题
- 【Java 基础】Java 泛型简单入门
- 小小的总结一下java异常处理和List、ArrayList、Vector、Set、HashSet、TreeSet集合的简单应用
- java使用itextpdf将图片转换成pdf的简单实例
- Java WebService 简单实例
- 利用Java编写简单的WebService实例