@SneakyThrows注解的作用及实现原理

16,927 阅读2分钟

@SneakyThrows注解的用途得从java的异常设计体系说起。 java中我们常见的2类异常。 1.普通Exception类,也就是我们常说的受检异常或者Checked Exception。 2.RuntimeException类,既运行时异常。 前者会强制要求抛出它的方法声明throws,调用者必须显示的去处理这个异常。设计的目的是为了提醒开发者处理一些场景中必然可能存在的异常情况。比如网络异常造成IOException。

但是现实,往往事与愿违。大部分情况下的异常,我们都是一路往外抛了事。(强制处理我也处理不了啊!臣妾做不到)所以渐渐的java程序员处理Exception的常见手段就是外面包一层RuntimeException,接着往上丢。这种解决思想尤其在Spring中到处出现。参见《Spring in Action》

try{

}catch(Exception e){
	throw new RuntimeException(e);
}

Lombok的@SneakyThrows就是为了消除这样的模板代码。 使用注解后不需要担心Exception的处理

import lombok.SneakyThrows;

import java.io.UnsupportedEncodingException;

public class SneakyThrowsExample implements Runnable {
    @SneakyThrows(UnsupportedEncodingException.class)
    public String utf8ToString(byte[] bytes) {
        return new String(bytes, "UTF-8");
    }

    @SneakyThrows
    public void run() {
        throw new Throwable();
    }
}

真正生成的代码

import lombok.Lombok;

import java.io.UnsupportedEncodingException;

public class SneakyThrowsExample implements Runnable {
    public String utf8ToString(byte[] bytes) {
        try {
            return new String(bytes, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw Lombok.sneakyThrow(e);
        }
    }

    public void run() {
        try {
            throw new Throwable();
        } catch (Throwable t) {
            throw Lombok.sneakyThrow(t);
        }
    }
}
Throws any throwable 'sneakily' - you don't need to catch it, nor declare that you throw it onwards.
The exception is still thrown - javac will just stop whining about it.

在这里插入图片描述

原理 显然魔法 藏在Lombok.sneakyThrow(t);中。可能大家都会以为这个方法就是new RuntimeException()之类的。然而事实并非如此。阅读代码可以看出整个方法其实最核心的逻辑是throw (T)t;,利用泛型将我们传入的Throwable强转为RuntimeException。虽然事实上我们不是RuntimeException。但是没关系。因为JVM并不关心这个。泛型最后存储为字节码时并没有泛型的信息。这样写只是为了骗过javac编译器。源码中注释有解释。

package lombok;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @SneakyThrow will avoid javac's insistence that you either catch or throw onward any checked exceptions that
 * statements in your method body declare they generate.
 * <p>
 * &#64;SneakyThrow does not silently swallow, wrap into RuntimeException, or otherwise modify any exceptions of the listed
 * checked exception types. The JVM does not check for the consistency of the checked exception system; javac does,
 * and this annotation lets you opt out of its mechanism.
 * <p>
 * Complete documentation is found at <a href="https://projectlombok.org/features/SneakyThrows">the project lombok features page for &#64;SneakyThrows</a>.
 * <p>
 * Example:
 * <pre>
 * &#64;SneakyThrows(UnsupportedEncodingException.class)
 * public void utf8ToString(byte[] bytes) {
 *     return new String(bytes, "UTF-8");
 * }
 * </pre>
 * 
 * Becomes:
 * <pre>
 * public void utf8ToString(byte[] bytes) {
 *     try {
 *         return new String(bytes, "UTF-8");
 *     } catch (UnsupportedEncodingException $uniqueName) {
 *         throw useMagicTrickeryToHideThisFromTheCompiler($uniqueName);
 *         // This trickery involves a bytecode transformer run automatically during the final stages of compilation;
 *         // there is no runtime dependency on lombok.
 *     }
 * </pre>
 */
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.SOURCE)
public @interface SneakyThrows {
	/** @return The exception type(s) you want to sneakily throw onward. */
	Class<? extends Throwable>[] value() default java.lang.Throwable.class;
	
	//The fully qualified name is used for java.lang.Throwable in the parameter only. This works around a bug in javac:
	//   presence of an annotation processor throws off the type resolver for some reason.
}

个人文章CSDN:blog.csdn.net/qq_43565087…