Java – dynamic proxy and exception checking

How do I make my dynamic agent throw a check exception?

I need a transparent wrapper for the interface, which sometimes throws check exceptions such as IOException No third party AOP may not write my own agent? All 20 methods of manually modifying the interface are not an option

Solution

You can use dynamic proxies As long as the checked exception is part of the interface, you can throw the checked exception from the call handler Otherwise, this is illegal and an undeclaredtowableexception will be created to wrap the thrown checked exception

interface A{
    void x() throws IOException;
}

A proxy = (A) newProxyInstance(classLoader,new Class<?>[]{A.class},new InvocationHandler() {      
        @Override
        public Object invoke(Object arg0,Method arg1,Object[] arg2) 
            throws Throwable {
            throw new IOException();
        }
   }
);
proxy.x();

Output:

Exception in thread "main" java.io.IOException
at X$1.invoke(X.java:19)
at $Proxy0.x(UnkNown Source)
at X.main(X.java:22)

For interface a, undeclared check exceptions:

interface A{
    void x();
}

Exception in thread "main" java.lang.reflect.UndeclaredThrowableException
  at $Proxy0.x(UnkNown Source)
  at X.main(X.java:22)
Caused by: java.io.IOException
  at X$1.invoke(X.java:19)
  ... 2 more
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>