使用注释通过运行时异常包装异常

rip*_*234 8 java annotations exception runtimeexception

有没有办法注释方法,所以抛出的所有异常都会自动转换为运行时异常?

@MagicAnnotation
// no throws clause!
void foo()
{
  throw new Exception("bar")'
}
Run Code Online (Sandbox Code Playgroud)

sin*_*pop 6

龙目岛项目@SneakyThrows可能就是你想要的.是不是真的包装你的异常(因为在很多情况下它可能是一个问题),它只是在编译期间不会抛出错误.

@SneakyThrows
void foo() {
    throw new Exception("bar")'
}
Run Code Online (Sandbox Code Playgroud)


Kam*_*šík 1

没办法做到这一点,至少现在我使用这样的解决方法(简化):

@SuppressWarnings({"rawtypes", "unchecked"})
public class Unchecked {
    public static interface UncheckedDefinitions{
        InputStream openStream();
        String readLine();
            ...
    }

  private static Class proxyClass = Proxy.getProxyClass(Unchecked.class.getClassLoader(), UncheckedDefinitions.class);

    public static UncheckedDefinitions unchecked(final Object target){
        try{
            return (UncheckedDefinitions) proxyClass.getConstructor(InvocationHandler.class).newInstance(new InvocationHandler(){
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if (target instanceof Class){
                        return MethodUtils.invokeExactStaticMethod((Class) target, method.getName(), args);
                    }

                  return MethodUtils.invokeExactMethod(target, method.getName(), args);
                }
            });
        }
        catch(Exception e){
            throw new RuntimeException(e);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用法如下:

import static ....Unchecked.*;

...

Writer w = ...;
unchecked(w).write(str, off, len);
Run Code Online (Sandbox Code Playgroud)

诀窍在于接口“从未完成”,每次我在某个地方需要未检查的方法时,我都会将该对象包装为未检查的并让 IDE 在接口中生成方法签名。

那么实现是通用的(反思性的和“慢”但通常足够快)

有一些代码后处理器和字节码编织器,但这对于我当前的项目来说是不可能的(甚至 aop 或其他基于 jvm 的语言),所以这是“发明的”。