java动态代理--代理接口无实现类
转载自 http://blog.csdn.net/zhu\_tianwei/article/details/40076391
使用通过接口定义,或解析接口注解等完成相关功能,如mybatis的SqlSession.getMapper的实现
1.接口定义
[java] view plain copy
- package cn.proxy;
- public interface IHello {
- String say(String aa);
- }
2.代理实现
[java] view plain copy
- package cn.proxy;
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
- /**
- * JDK动态代理代理类
- *
- */
- @SuppressWarnings(“unchecked”)
- public class 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 “调用返回值”;
- }
- public static
T newMapperProxy(Class mapperInterface) { - ClassLoader classLoader = mapperInterface.getClassLoader();
- Class<?>[] interfaces = new Class[]{mapperInterface};
- FacadeProxy proxy = new FacadeProxy();
- return (T) Proxy.newProxyInstance(classLoader, interfaces, proxy);
- }
- }
4.运行
[java] view plain copy
- package cn.proxy;
- public class Test {
- public static void main(String[] args) {
- IHello hello = FacadeProxy.newMapperProxy(IHello.class);
- System.out.println(hello.say(“hello world”));
- }
- }
运行结果:
[plain] view plain copy
- 接口方法调用开始
- method toGenericString:public abstract java.lang.String cn.proxy.IHello.say(java.lang.String)
- method name:say
- method args:hello world
- 接口方法调用结束
- 调用返回值
还没有评论,来说两句吧...