更好
package com.gc.action; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import org.apache.log4j.Level; import org.apache.log4j.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 { Object result = null; try { logger.log(Level.INFO, args[0] + "开始添加"); result = method.invoke(delegate, args); logger.log(Level.INFO, args[0] + "数据添加成功"); } catch (Exception e) { logger.log(Level.INFO, e.toString()); } return result; } }
package com.gc.impl; import org.apache.log4j.Level; public interface TimeBookInterface { public void doAuditing(String name); //刚开始时,这里一直出错,后添加import org.apache.log4j.Level;OK! }
package com.gc.action; import com.gc.impl.TimeBookInterface; public class TimeBook implements TimeBookInterface{ public void doAuditing(String name) { System.out.println("好的"); } }
package com.gc.test; import com.gc.action.LogProxy; import com.gc.action.TimeBook; import com.gc.impl.TimeBookInterface; public class TestHelloWorld { public static void main(String args[]) //throws InstantiationException,IllegalAccessException,ClassNotFoundException { LogProxy logProxy=new LogProxy(); TimeBookInterface timeBookProxy=(TimeBookInterface)logProxy.bind(new TimeBook()); timeBookProxy.doAuditing("张三"); } }