标签:ice public targe override span style 创建 代理 port
先创建一个被代理对象,该对象必须继承一个接口(否则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 }
标签:ice public targe override span style 创建 代理 port
原文地址:http://www.cnblogs.com/popcornya/p/6906455.html