简体   繁体   English

龙目岛注释@SneakyThrows

[英]lombok annotation @SneakyThrows

I have question about @SneakyThrows can be used to sneakily throw checked exceptions without actually declaring this in your method's throws clause.我对 @SneakyThrows 可用于偷偷地抛出已检查的异常有疑问,而无需在您的方法的 throws 子句中实际声明这一点。

public class Demo {

    public static void main(String[] args) {

    }

    private void throwE() throws ClassNotFoundException {

    }

    @SneakyThrows
    private void t() {
        throwE();
    }
}

Here is generate by lombok.这里是由 lombok 生成的。

public class Demo {
    public Demo() {
    }

    public static void main(String[] args) throws IOException {
    }

    private void throwE() throws ClassNotFoundException {
    }

    private void t() {
        try {
            this.throwE();
        } catch (Throwable var2) {
            throw var2;
        }
    }
}

Why the code generate by lombok can fakes out the compiler without declaring throws clause.为什么 lombok 生成的代码可以在不声明 throws 子句的情况下伪造编译器。

See @SneakyThrows , it uses Lombok.sneakyThrow(t) and not var2 :参见@SneakyThrows ,它使用Lombok.sneakyThrow(t)而不是var2

 public void run() { try { throw new Throwable(); } catch (Throwable t) { throw Lombok.sneakyThrow(t); } }

The answer is that Lombok cheats the compiler - but what you've shown is a decompiled version of the compiled byte code - and the JVM running the byte code does not distinguish between checked and unchecked exceptions: it does not care.答案是 Lombok 欺骗了编译器——但你所展示的是编译字节码的反编译版本——并且运行字节码的 JVM 不区分已检查和未检查的异常:它不在乎。

If you take a look at Lombok.sneakyThrow() source code, you'll see that it eventually does two things:如果您查看Lombok.sneakyThrow()源代码,您会发现它最终会做两件事:

  1. A null check空检查
  2. A cast一个演员

Both are removed as part of the compilation, which is why your decompiled code simply rethrows the exception.两者都作为编译的一部分被删除,这就是为什么您的反编译代码只是重新抛出异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM