Java的代理机制

//LogProxy.java

package com.wdf.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

public class LogProxy implements InvocationHandler{
    private Logger logger=Logger.getLogger(this.getClass().getName());
    private Object delegate;
    public Object bind(Object delegate){
     this.delegate=delegate;
     return Proxy.newProxyInstance(delegate.getClass().getClassLoader(), delegate.getClass().getInterfaces(), this);
    }
public Object invoke(Object proxy, Method method, Object[] args)
   throws Throwable {
  // TODO Auto-generated method stub
  Object result=null;
  SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  format.setLenient(false);
  String currentDate=format.format(new Date());
  logger.log(Level.INFO, currentDate);
  result=method.invoke(delegate, args);
  logger.log(Level.INFO, "end----");
  return result;
}

}

//TimeBookInterface.java

package com.wdf.book;

public interface TimeBookInterface {
  public void doAuditing(String name);
}
TimeBook.java

package com.wdf.book;

public class TimeBook implements TimeBookInterface{

public void doAuditing(String name) {
  // TODO Auto-generated method stub
  System.out.println(name);
}

}

//test.java

package com.wdf.book;

import com.wdf.proxy.LogProxy;

public class test {

/**
  * @param args
  */
public static void main(String[] args) {
  // TODO Auto-generated method stub
    LogProxy logproxy=new LogProxy();
    TimeBookInterface tbi=(TimeBookInterface)logproxy.bind(new TimeBook());
    tbi.doAuditing("wonderful");
  
}

}

你可能感兴趣的:(java)