一、代码实现
1. 编写UserService接口
import java. util. List ; public interface UserService { void login ( String userName, String password) ; List < String > getUserList ( ) ;
}
2. 编写UserService接口实现类
import java. util. Arrays ;
import java. util. List ; public class UserServiceImpl implements UserService { @Override public void login ( String userName, String password) { if ( userName. equals ( "Rem" ) && password. equals ( "5201314" ) ) { System . out. println ( "登陆成功,欢迎您蕾姆~" ) ; } } @Override public List < String > getUserList ( ) { List < String > users = Arrays . asList ( "蕾姆" , "雪乃" , "三玖" , "藤原千花" ) ; System . out. println ( "查询到的用户是:" + users) ; return users; }
}
3. 编写代理工具类
import java. lang. reflect. InvocationHandler ;
import java. lang. reflect. Method ;
import java. lang. reflect. Proxy ;
public class ProxyUtils { public static UserService createProxy ( UserService userService) { UserService userServiceProxy = ( UserService ) Proxy . newProxyInstance ( ProxyUtils . class . getClassLoader ( ) , new Class [ ] { UserService . class } , new InvocationHandler ( ) { @Override public Object invoke ( Object proxy, Method method, Object [ ] args) throws Throwable { if ( method. getName ( ) . equals ( "login" ) || method. getName ( ) . equals ( "getUserList" ) ) { long startTime = System . currentTimeMillis ( ) ; Object res = method. invoke ( userService, args) ; long endTime = System . currentTimeMillis ( ) ; System . out. println ( method. getName ( ) + "方法执行时间为:" + ( endTime - startTime) / 1000.0 + "s" ) ; return res; } else { return method. invoke ( userService, args) ; } } } ) ; return userServiceProxy; }
}
4. 编写测试类
public class UserTest { public static void main ( String [ ] args) { UserService userService = ProxyUtils . createProxy ( new UserServiceImpl ( ) ) ; userService. login ( "Rem" , "5201314" ) ; System . out. println ( "======================================" ) ; userService. getUserList ( ) ; }
}
5. 实现结果
二、参考资料
【黑马磊哥】Java动态代理深入剖析,真正搞懂Java核心设计模式:代理设计模式
三、后记
最近在看动态代理相关的教程,写了一个demo,分享给大家,后续还会更新更深层次的Java动态代理解析。 要是文章对您有帮助,欢迎点赞、收藏、评论、关注!