07. 《Lombok 实战 —— @SneakyThrows & @Synchronized》

本文介绍了Lombok的@SneakyThrows和@synchronized注解的实战使用和原理。@SneakyThrows允许不声明异常直接抛出,@Synchronized提供了一种更安全的同步锁机制,同时讲解了它们的源码解析和特殊用法。
摘要由CSDN通过智能技术生成

《Lombok 实战 —— @SneakyThrows & @Synchronized》

@SneakyThrows

To boldly throw checked exceptions where no one has thrown them before!

1.1 @SneakyThrows 实战使用

@SneakyThrows 可用于偷偷抛出checked exception,而无需在方法上的throws子句中声明需要抛出的异常。
lombok生成的代码,不会忽略,不会包装,不会替换或以其他方式修改抛出的checked exception,而是将 checked exception 看做unchecked exception,不处理,直接扔掉。

那么lombok是如何工作的呢?

在JVM(类文件)级别上,无论方法throw什么异常,lombok都可以抛出所有异常(无论是否是检查时异常),如下面一个简单的示例:

public class SneakyThrowsTest {
   
    public static void main(String[] args) {
   
        throwException();
    }
    @SneakyThrows
    public static void throwException() {
   
        String str  = null;
        String[] split = str.split(",");
        System.out.println(split);
    }
}

// 编译后:
public class SneakyThrowsTest {
   
    public SneakyThrowsTest() {
   }

    public static void main(String[] args) {
   
        throwException();
    }
    public static void throwException() {
   
        try {
   
            String str = null;
            String[] split = ((String)str).split(",");
            System.out.println(split);
        } 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

「已注销」

滚蛋吧,结核菌!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值