1. 程式人生 > 其它 >@SneakyThrows註解的作用及實現原理

@SneakyThrows註解的作用及實現原理

@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.
}