动态代理

来自:http://203.208.39.99/search?q=cache:0G_Ej1uHhFEJ:www.javaresearch.org/article/78993.htm+java%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86&hl=zh-CN&ct=clnk&cd=4&gl=cn&st_usg=ALhdy2-JyZZZvvc4iOqWU0LqQWdj4ozDOw

 

类1:

package readxml;

public interface BusinessInterface {
 public void processBusiness();
}

 

类2:

package readxml;

import java.util.logging.Logger;

public class BusinessObject implements BusinessInterface {

 // private Logger logger = Logger.getLogger(this.getClass().getName());
 //
 // public void processBusiness() {
 // try {
 // logger.info("start to processing...");
 // // business logic here。
 // System.out.println("here is business logic");
 // logger.info("end processing...");
 // } catch (Exception e) {
 // logger.info("exception happends...");
 // // exception handling
 // }
 // }
 private Logger logger = Logger.getLogger(this.getClass().getName());

 public void processBusiness() {
  // business processing
  System.out.println("here is business logic");
 }

}

 

类3:

package readxml;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.logging.Logger;

public class LogHandler implements InvocationHandler {

 private Logger logger = Logger.getLogger(this.getClass().getName());
 private Object delegate;

 public LogHandler(Object delegate) {
  this.delegate = delegate;
 }

 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  Object o = null;
  try {
   logger.info("method stats..." + method);
   o = method.invoke(delegate, args);
   logger.info("method ends..." + method);
  } catch (Exception e) {
   logger.info("Exception happends...");
  }
  return o;
 }
}

 

类4:

package readxml;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

public class Test {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  BusinessInterface businessImp = new BusinessObject();
  InvocationHandler handler = new LogHandler(businessImp);
  BusinessInterface proxy = (BusinessInterface) Proxy.newProxyInstance(businessImp.getClass().getClassLoader(), businessImp.getClass().getInterfaces(), handler);
  proxy.processBusiness();

 }

}

 

 

 

 

 

关于classloader:

http://203.208.39.99/search?q=cache:A_oL2tFoF20J:www.blogjava.net/clraychen/archive/2008/02/20/180868.html+java+ClassLoader%E6%98%AF&hl=zh-CN&ct=clnk&cd=1&gl=cn&st_usg=ALhdy2_93Ey5v8KVn7YShC8sWUdPx3sHAg

你可能感兴趣的:(exception,object,ClassLoader,cache,Class,interface)