首页 > 代码库 > JDK的动态代理
JDK的动态代理
先创建一个被代理对象,该对象必须继承一个接口(否则jdk无法产生动态代理)
接口:
1 package com.bxw.service; 2 3 public interface UserService { 4 public String getName(int id); 5 public Integer getAge(int id); 6 }
被代理的对象:
1 package com.bxw.serviceImpl; 2 3 import com.bxw.service.UserService; 4 5 public class UserServiceImpl implements UserService{ 6 7 @Override 8 public String getName(int id) { 9 System.out.println("---getNmae---"); 10 return "Tom"; 11 } 12 13 @Override 14 public Integer getAge(int id) { 15 System.out.println("---getAge---"); 16 return 17; 17 } 18 19 }
Handler:
1 package com.bxw.invocation; 2 3 import java.lang.reflect.InvocationHandler; 4 import java.lang.reflect.Method; 5 6 public class MyInvocationHandler implements InvocationHandler { 7 //动态代理要有一个被代理的对象 8 private Object target; 9 10 MyInvocationHandler() { 11 super(); 12 } 13 14 public MyInvocationHandler(Object target) { 15 super(); 16 this.target = target; 17 } 18 19 @Override 20 public Object invoke(Object o, Method method, Object[] args) throws Throwable { 21 if("getName".equals(method.getName())){ 22 System.out.println("++++++before " + method.getName() + "++++++"); 23 Object result = method.invoke(target, args); 24 System.out.println("++++++after " + method.getName() + "++++++"); 25 return result; 26 }else{ 27 Object result = method.invoke(target, args); 28 return result; 29 } 30 31 } 32 }
Test:
1 package com.bxw.test; 2 3 import java.lang.reflect.InvocationHandler; 4 import java.lang.reflect.Proxy; 5 6 import com.bxw.invocation.MyInvocationHandler; 7 import com.bxw.service.UserService; 8 import com.bxw.serviceImpl.UserServiceImpl; 9 10 /** 11 * jdk要实现动态代理那么该类必须实现一个接口 12 * @author Admin 13 * 14 */ 15 public class TestDemo { 16 public static void main(String[] args) { 17 UserService userService = new UserServiceImpl(); //被代理对象 18 InvocationHandler invocationHandler = new MyInvocationHandler(userService); 19 //classLoader,interface,产生业务逻辑的Hanfler 20 UserService userServiceProxy = (UserService)Proxy.newProxyInstance(userService.getClass().getClassLoader(), 21 userService.getClass().getInterfaces(), invocationHandler);//产生的代理对象 22 System.out.println(userServiceProxy.getName(1)); 23 System.out.println(userServiceProxy.getAge(1)); 24 } 25 }
JDK的动态代理
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。