接口: public interface IUserService { public void saveUser(String username,String password); public void updateUser(String username,String password); public void deleteUser(String username); public String findUser(); } 目标对象: public class UserServiceImpl implements IUserService { @Override public void saveUser(String username, String password) { System.out.println("保存用户【"+username+"】,密码是【"+password+"】"); } @Override public void updateUser(String username, String password) { System.out.println("更新用户【"+username+"】,密码是【"+password+"】"); } @Override public void deleteUser(String username) { System.out.println("删除用户【"+username+"】"); } @Override public String findUser() { System.out.println("查询用户,返回王老五"); return "王老五"; } } 代理对象: public class JdkDaili implements InvocationHandler{ Object userServiceImpl; @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // TODO Auto-generated method stub System.out.println(proxy.getClass()); System.out.println(method.getName()); if (args.length>0&&args!=null) { for (Object object : args) { System.out.println(object); } } return method.invoke(userServiceImpl, args); } public Object createrDaiLi(Object userServiceImpl) { this.userServiceImpl=userServiceImpl; return Proxy.newProxyInstance(this.userServiceImpl.getClass().getClassLoader(), this.userServiceImpl.getClass().getInterfaces(), this ); } } 测试: public static void main(String[] args) { //需求:在访问保存和更新的方法之前,先让你执行一个校验,使用代理对象完成 JdkDaili jdkDaili=new JdkDaili();//用目标对象创建代理对象 IUserService iService=(IUserService) jdkDaili.createrDaiLi(new UserServiceImpl());//代理对象执行 代理类里面的invoke()方法,返回return method.invoke(目标对象, 目标对象的方法的参数); iService.saveUser("hgiohr", "51684"); }
时间: 2024-10-07 23:59:05