【发布时间】:2021-11-01 14:10:37
【问题描述】:
我试图了解 Lombok 中的 @SneakyThrows 注释实际上是如何工作的。
从this SO answer,我可以收集到它在后台使用Lombok.sneakyThrows() 方法。
Lombok.sneakyThrows()的代码如下:
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;
}
据我所知,它所做的只是将其转换为 java.lang.RuntimeException,因此编译器不会抱怨。
但这不应该在技术上给出ClassCastException吗?
例如:
public static void main(String args[]) {
Throwable i = new InterruptedException();
RuntimeException rr = (RuntimeException) i;
}
以上代码导致 ClassCastException。
那为什么龙目岛没有发生同样的事情呢?
【问题讨论】:
-
您关于强制转换为 RuntimeException 的基本假设是错误的。请参阅文档。
-
请参阅gamlor.info/wordpress/2010/02/…,其中详细介绍了此 hack。
标签: java generics exception lombok checked-exceptions