Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

利用泛型的类型擦除,在方法不声明 throws 异常时,抛出 checked 异常 #226

Open
Bpazy opened this issue May 24, 2022 · 0 comments

Comments

@Bpazy
Copy link
Owner

Bpazy commented May 24, 2022

参考 org.apache.commons.lang3.exception.ExceptionUtils 的做法:

    public static <R> R rethrow(Throwable throwable) {
        // claim that the typeErasure invocation throws a RuntimeException
        return ExceptionUtils.<R, RuntimeException> typeErasure(throwable);
    }

    @SuppressWarnings("unchecked")
    private static <R, T extends Throwable> R typeErasure(Throwable throwable) throws T {
        throw (T) throwable;
    }

测试:

public class Main {
    public static void main(String[] args) {
        try {
            throw new Exception();
        } catch (Exception e) {
            ExceptionUtils.rethrow(e);
        }
    }
}

输出:

Exception in thread "main" java.lang.Exception
	at com.github.bpazy.test.Main.main(Main.java:14)
@Bpazy Bpazy added the Java label May 24, 2022
@Bpazy Bpazy removed the Java label Dec 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant