动态代理
主营业务接口:
public interface IUserManger { public void AddUser(String UserName, String Password); public void ModifyUser(int id, String UserName, String Password); }
接口实现类:
public class UserManagerImpl implements IUserManager{ public void addUser(String username, String password) { System.out.println("=========UserManagerImpl.addUser()==========="); } public void modifyUser(int id, String username, String password) { System.out.println("=========UserManagerImpl.modifyUser()==========="); } }
继承invocationHandler的类:
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; //帮助我们动态的生成代理对象JDK1.5 public class SecurityHandler implements InvocationHandler { private Object targetObject;//目标对象 //生成代理对象 public Object proxyInstance(Object paramObject){ this.targetObject = paramObject; return Proxy.newProxyInstance( this.targetObject.getClass().getClassLoader(), this.targetObject.getClass().getInterfaces(), this);//得到目标加载器实现invocationHandler的类,也就是本类 } //传入代理对象,目标对象的方法,方法参数,代理方法与目标方法都实现了IUserManager public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object resultObj = null; checkSecurity(); try{ resultObj = method.invoke(this.targetObject,args);//递归调用 }catch (Exception ex){ ex.printStackTrace(); } return resultObj; } public void checkSecurity(){ System.out.println("=======checkSecurity()=========="); } }
测试类:
public class Client { public static void main(String[] args) { SecurityHandler securityHandler = new SecurityHandler(); IUserManager iUserManager = (IUserManager) securityHandler.proxyInstance(new UserManagerImpl()); iUserManager.addUser("abc","123"); } }