Java的类是这样的
public class Demo {
public static void main(String[] args) {
}
private void throwE() throws ClassNotFoundException {
}
@SneakyThrows
private void t() {
throwE();
}
}
生成的class文件是这样的
public class Demo {
public Demo() {
}
public static void main(String[] args) {
}
private void throwE() throws ClassNotFoundException {
}
private void t() {
try {
this.throwE();
} catch (Throwable var2) {
throw var2;
}
}
}
Lombok 欺骗了编译器。 通过查看Lombok.sneakyThrow()的源码
package lombok;
public class Lombok {
public static RuntimeException sneakyThrow(Throwable t) {
if (t == null) throw new NullPointerException("t");
return Lombok.<RuntimeException>sneakyThrow0(t);
}
@SuppressWarnings("unchecked")
private static <T extends Throwable> T sneakyThrow0(Throwable t) throws T {
throw (T)t;
}
public static <T> T preventNullAnalysis(T value) {
return value;
}
public static <T> T checkNotNull(T value, String message) {
if (value == null) throw new NullPointerException(message);
return value;
}
}
你会发现它最终做了两件事: 空检查 重铸 两者都作为编译的一部分被删除,这就是为什么反编译代码只是重新抛出异常 这样可以用@SneakyThrows代替try{}catch{}
|