Netty是个值得花时间学习的框架,即使一个不起眼的程序,都有值得深入学习的地方。比如:io.netty.util.internal.PlatformDependent类中,对异常的处理就非常巧妙。
经常会碰到这种情况,实现一个接口,接口签名是没有申明异常的。但在实现中却需要捕获异常。比如:guava包中的通用接口
public interface Supplier<T> {
/**
* Retrieves an instance of the appropriate type.
* The returned object may or
* may not be a new instance, depending on the implementation.
*
* @return an instance of the appropriate type
*/
T get();
}
我们实现这个接口,假设需要调用JDBC接口获取数据库的数据:
public class JdbcSupplier implements Supplier<Map> {
Map get() {
try {
//调用JDBC接口
//封装数据,return
} catch (SQLException e) {
throw new RuntimeException (e);
}
}
}
我们不得不捕获异常,并转换为RuntimeException,才能编译通过,但丢失了最初的异常面目。这类问题一般有两种做法。就像PlatformDependent类的throwException方法。
1.利用sun.misc.Unsafe的throwException方法;
2.利用泛型的擦拭,Raises an exception bypassing compiler checks for checked exceptions
public static void throwException(Throwable t) {
if (hasUnsafe()) {
PlatformDependent0.throwException(t);
} else {
//显式指定异常为RuntimeException,欺骗编译器通过编译;
//编译后会擦拭掉泛型信息,变成具体的受检查异常;
PlatformDependent.<RuntimeException>throwException0(t);
}
}
static void throwException(Throwable t) {
UNSAFE.throwException(t);
}
@SuppressWarnings("unchecked")
private static <E extends Throwable> void throwException0(Throwable t) throws E {
throw (E) t;
}
分享到:
相关推荐
Netty中文指南教程 详细描述netty的官方文档,中文版
netty 4.1中文.CHM,chm格式,中文api,开发netty的中文工具书
netty 4.1 中文.CHM,开发netty的中文工具书 帮助文档,中文版netty
Netty在Android开发中的应用实战系列(三)——— 心跳处理 | 断线重连:https://azhon.blog.csdn.net/article/details/100941312 Netty在Android开发中的应用实战系列(四)——— 粘包 | 拆包 处理:...
netty中的多线程并发应用,
Netty_中文技术文档,Netty操作指南
netty中文开发指南,netty是java基于事件的tcp/ip通信技术。
Netty应用中文详解
netty案例,netty4.1中级拓展篇十《Netty接收发送多种协议消息类型的通信处理方案》源码 ...
很多学习netty的小伙伴,感觉看原生态纯英文文档非常吃力,而且很多语义不懂,这使得学习变得枯燥乏味,这次分享的资源就可以完美解决这个问题,让你能够更方便快捷的学习并掌握这门技术
基于Netty框架开发的Modbus源代码。支持 * READ COILS | 0x01 * READ DISCRETE INPUTS | 0x02 * READ HOLDING REGISTERS | 0x03 * READ INPUT REGISTERS | 0x04 * WRITE SINGLE COIL | 0x05 * WRITE SINGLE REGISTER...
springboot整合 netty做心跳检测 springboot整合 netty做心跳检测 springboot整合 netty做心跳检测 springboot整合 netty做心跳检测 springboot整合 netty做心跳检测 springboot整合 netty做心跳检测 springboot整合...
赠送jar包:netty-all-4.1.17.Final.jar; 赠送原API文档:netty-all-4.1.17.Final-javadoc.jar; 赠送源代码:netty-all-4.1.17.Final-sources.jar; 赠送Maven依赖信息文件:netty-all-4.1.17.Final.pom; 包含...
Netty-API-文档中文版,学习Netty再也不怕看不懂英文了
netty-3.1官网学习手册,中文版
赠送jar包:netty-3.10.5.Final.jar; 赠送原API文档:netty-3.10.5.Final-javadoc.jar; 赠送源代码:netty-3.10.5.Final-sources.jar; 赠送Maven依赖信息文件:netty-3.10.5.Final.pom; 包含翻译后的API文档:...
netty3.1 中文用户手册; netty3.1 中文用户手册;
赠送jar包:reactor-netty-http-1.0.11.jar; 赠送原API文档:reactor-netty-http-1.0.11-javadoc.jar; 赠送源代码:reactor-netty-...人性化翻译,文档中的代码和结构保持不变,注释和说明精准翻译,请放心使用。
Java网络编程框架,学写使用Netty开发Socket服务
一个netty的中文文档和demo。 。