• Lombok @SneakyThrows注解


    Lombok @SneakyThrows注解

    这个注解我的理解就是代替 throws,当使用@SneakyThrows时就是throws所有异常,@SneakyThrows({InterruptedException.class, IOException.class})@SneakyThrows(InterruptedException.class)这类写法就是指定异常向上抛出。如果有理解不对的欢迎在评论区指出。

    1、@SneakyThrows与throws区别1

    使用@SneakyThrows注解标注的方法

        @SneakyThrows
        public static void main(String[] args) {
            Class clz = Class.forName("com.woshild.derek_ld.lombok.SneakyThrowsTest");
            System.out.println(clz.getName());
    
            Thread.sleep(3000);
            System.out.println("3秒已过。。。");
        }
    
    

    代码编译后会是这样的

        public static void main(String[] args) {
            try {
                Class clz = Class.forName("com.woshild.derek_ld.lombok.SneakyThrowsTest");
                System.out.println(clz.getName());
                Thread.sleep(3000L);
                System.out.println("3秒已过。。。");
            } catch (Throwable var2) {
                throw var2;
            }
        }
    

    它并不是做了简单的throws,但是做的还是把异常向上抛出。

    实现原理如下:

      public static RuntimeException sneakyThrow(Throwable t) {
            if (t == null) throw new NullPointerException("t");
            return Lombok.<RuntimeException>sneakyThrow0(t);
        }
    
        private static <T extends Throwable> T sneakyThrow0(Throwable t) throws T {
            throw (T)t;
        }
    
    	...
    }
    

    2、@SneakyThrows与throws区别2

    如果@SneakyThrows就是实现throws的功能,那为什么不直接用throws呢?我们写业务类时,通常会写接口,如果使用throws,那么在接口和实现类都需要加上throws,但使用SneakyThrows就没有这个限制。

    参考:Lombok之@SneakyThrows

  • 相关阅读:
    centos 6,7 上cgroup资源限制使用举例
    redis sentinel哨兵的使用
    redis发布-订阅
    Golang cpu的使用设置--GOMAXPROCS
    Golang 端口复用测试
    Golang client绑定本地IP和端口
    Go并发控制--context的使用
    Go 并发控制--WaitGroup的使用
    go thrift报错问题--WriteStructEnd
    secureCRT上传本地文件到虚拟机
  • 原文地址:https://www.cnblogs.com/zhangruifeng/p/16086720.html
Copyright © 2020-2023  润新知