java動態代理--代理介面無實現類
阿新 • • 發佈:2019-02-03
轉載自 http://blog.csdn.net/zhu_tianwei/article/details/40076391
使用通過介面定義,或解析介面註解等完成相關功能,如mybatis的SqlSession.getMapper的實現
1.介面定義
- package cn.proxy;
- publicinterface IHello {
- String say(String aa);
- }
2.代理實現
- package cn.proxy;
- import java.lang.reflect.InvocationHandler;
-
import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
- /**
- * JDK動態代理代理類
- *
- */
- @SuppressWarnings("unchecked")
- publicclass FacadeProxy implements InvocationHandler {
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
-
System.out.println("介面方法呼叫開始"
- //執行方法
- System.out.println("method toGenericString:"+method.toGenericString());
- System.out.println("method name:"+method.getName());
- System.out.println("method args:"+(String)args[0]);
- System.out.println("介面方法呼叫結束");
- return"呼叫返回值";
-
}
- publicstatic <T> T newMapperProxy(Class<T> mapperInterface) {
- ClassLoader classLoader = mapperInterface.getClassLoader();
- Class<?>[] interfaces = new Class[]{mapperInterface};
- FacadeProxy proxy = new FacadeProxy();
- return (T) Proxy.newProxyInstance(classLoader, interfaces, proxy);
- }
- }
- package cn.proxy;
- publicclass Test {
- publicstaticvoid main(String[] args) {
- IHello hello = FacadeProxy.newMapperProxy(IHello.class);
- System.out.println(hello.say("hello world"));
- }
- }
執行結果:
- 介面方法呼叫開始
- method toGenericString:public abstract java.lang.String cn.proxy.IHello.say(java.lang.String)
- method name:say
- method args:hello world
- 介面方法呼叫結束
- 呼叫返回值