本来想自己写一个日志的,发现有位老兄写的很好,我就不用费事,直接贴过来做笔记好了。
==========================================================
[转自:
http://publishblog.blogdriver.com/blog/tb.b?diaryID=842351
]
[Java]使用Proxy和InvocationHandler实现代理器模式
package com.zj.gof.proxy;
public interface StudentInfoService {
void findInfo(String studentName);
}
package com.zj.gof.proxy;
public class StudentInfoServiceImpl implements StudentInfoService {
public void findInfo(String name) {
System.out.println("你目前输入的名字是:" + name);
}
}
package com.zj.gof.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.apache.log4j.Logger;
public class LogHandler implements InvocationHandler {
private Object proxyObj;
private static Logger log=Logger.getLogger(LogHandler.class);
public Object bind(Object obj){
this.proxyObj=obj;
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),this);
}
public Object invoke(Object proxy,Method method,Object[] args) throws Throwable{
Object result=null;
try{
//请在这里插入代码,在方法前调用
log.info("调用log日志方法"+method.getName());
result=method.invoke(proxyObj,args); //原方法
//请在这里插入代码,方法后调用
}catch(Exception e){
e.printStackTrace();
}
return result;
}
}
注意:通过InvocationHandler接口实现的代理器只能代理接口方法.
(这点在InvocationHandler的注解中有说明)
package com.zj.gof.proxy;
public class LogFactory {
private static Object getClassInstance(String clzName) {
Object obj = null;
try {
Class cls = Class.forName(clzName);
obj = (Object) cls.newInstance();
} catch (ClassNotFoundException cnfe) {
System.out.println("ClassNotFoundException:" + cnfe.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
public static Object getAOPProxyedObject(String clzName) {
Object proxy = null;
LogHandler handler = new LogHandler();
Object obj = getClassInstance(clzName);
if (obj != null) {
proxy = handler.bind(obj);
} else {
System.out.println("Can't get the proxyobj");
//throw
}
return proxy;
}
}
package com.zj.gof.proxy;
public class MainTest {
public static void main(String[] args) {
// PropertyConfigurator.configure("d:/log4j.properties");
BasicConfigurator.configure();
StudentInfoService studentInfo = (StudentInfoService) LogFactory
.getAOPProxyedObject("com.zj.gof.proxy.StudentInfoServiceImpl");
studentInfo.findInfo("阿飞");
}
}
0 [main] INFO root - 调用log日志方法findInfo
你目前输入的名字是:阿飞