java动态代理--代理接口无实现类

悠悠 2022-06-01 13:38 292阅读 0赞

转载自 http://blog.csdn.net/zhu\_tianwei/article/details/40076391

使用通过接口定义,或解析接口注解等完成相关功能,如mybatis的SqlSession.getMapper的实现

1.接口定义

[java] view plain copy

  1. package cn.proxy;
  2. public interface IHello {
  3. String say(String aa);
  4. }

2.代理实现

[java] view plain copy

  1. package cn.proxy;
  2. import java.lang.reflect.InvocationHandler;
  3. import java.lang.reflect.Method;
  4. import java.lang.reflect.Proxy;
  5. /**
  6. * JDK动态代理代理类
  7. *
  8. */
  9. @SuppressWarnings(“unchecked”)
  10. public class FacadeProxy implements InvocationHandler {
  11. @Override
  12. public Object invoke(Object proxy, Method method, Object[] args)
  13. throws Throwable {
  14. System.out.println(“接口方法调用开始”);
  15. //执行方法
  16. System.out.println(“method toGenericString:”+method.toGenericString());
  17. System.out.println(“method name:”+method.getName());
  18. System.out.println(“method args:”+(String)args[0]);
  19. System.out.println(“接口方法调用结束”);
  20. return “调用返回值”;
  21. }
  22. public static T newMapperProxy(Class mapperInterface) {
  23. ClassLoader classLoader = mapperInterface.getClassLoader();
  24. Class<?>[] interfaces = new Class[]{mapperInterface};
  25. FacadeProxy proxy = new FacadeProxy();
  26. return (T) Proxy.newProxyInstance(classLoader, interfaces, proxy);
  27. }
  28. }

4.运行

[java] view plain copy

  1. package cn.proxy;
  2. public class Test {
  3. public static void main(String[] args) {
  4. IHello hello = FacadeProxy.newMapperProxy(IHello.class);
  5. System.out.println(hello.say(“hello world”));
  6. }
  7. }

运行结果:

[plain] view plain copy

  1. 接口方法调用开始
  2. method toGenericString:public abstract java.lang.String cn.proxy.IHello.say(java.lang.String)
  3. method name:say
  4. method args:hello world
  5. 接口方法调用结束
  6. 调用返回值

发表评论

表情:
评论列表 (有 0 条评论,292人围观)

还没有评论,来说两句吧...

相关阅读