`
jnullpointer
  • 浏览: 15583 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

Netty中PlatformDependent绕开受检查异常处理

阅读更多
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;
    }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics