动态代理

 

JDK动态代理

 

public class LogHandler implements InvocationHandler {
 
 private Object targetObject;
 
 public Object newProxyInstance(Object targetObject) {
  this.targetObject = targetObject;
  return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(),
          targetObject.getClass().getInterfaces(), this);
 }
 
 public Object invoke(Object proxy, Method method, Object[] args)
   throws Throwable {
  System.out.println("start-->>" + method.getName());
  for (int i=0; i<args.length; i++) {
   System.out.println(args[i]);
  }
  Object ret = null;
  try {
   //调用目标方法
   ret = method.invoke(targetObject, args);
   System.out.println("success-->>" + method.getName());
  }catch(Exception e) {
   e.printStackTrace();
   System.out.println("error-->>" + method.getName());
   throw e;
  }
  return ret;
 }

}

 

----------------------------------------------------------------------------------------------------------------------------

public class Client {


 public static void main(String[] args) {


  LogHandler logHandler = new LogHandler();
  UserManager userManager = (UserManager)logHandler.newProxyInstance(new UserManagerImpl());
  String name = userManager.findUser("0001");
  System.out.println("Client.main() --- " + name);


 }

}

 

 

 

你可能感兴趣的:(jdk)