1. output function name start time at method start
2. output the function name end time and method time at the end of the method.
Then paste my texture again to show the result
Completed successfully.
At this time, we should also look at how I completed it. Please pay attention to the contents of the black text
Other codes are the same as those in the previous article. A new class is added here.
1. EventHandler. java
========================================================== ======================================
Package org. dong. core;
Import java. lang. reflect. InvocationHandler;
Import java. lang. reflect. Method;
Import java. util. Date;
Public class EventHandler implements InvocationHandler {
Private Object delegate;
Public EventHandler (Object delegatec)
{
// Upload the objects to be proxies
This. delegate = delegatec;
}
Public Object invoke (Object proxy, Method method, Object [] args)
Throws Throwable {
Object obj = null;
Long startTime = System. currentTimeMillis ();
// Before doing this, I can add some code. Here is where the function is implemented.
Date dt = new Date ();
System. err. println (method + "begin" + "@" + dt. toString ());
Obj = method. invoke (delegate, args); // Hey, my XX, proxy process
// I can add some code
Dt = new Date ();
Long endTime = System. currentTimeMillis ();
System. err. println (method + "end" + "@" +
Dt. toString () + "time" + (endTime-startTime) + "ms ");
Return obj; // kick the finished part out.
}
}
Then I modified the corresponding BeanFactory implementation class to complete our functions.
Package org. dong. core;
Import java. lang. reflect. InvocationHandler;
Import java. lang. reflect. Proxy;
Public class XmlBeanFactory implements BeanFactory {
Private String ResPath;
Private static DongXmlOp XmlOp;
Public XmlBeanFactory (Resource Res ){
ResPath = Res. GetResPath ();
XmlOp = new DongXmlOp (ResPath );
}
Public Object getBean (String string ){
Bean tmpBean;
TmpBean = XmlOp. GetBeanByID (string );
Try {
Class rtnClass = Class. forName (tmpBean. getBeanClass ());
// TempBean. getBeanClass () = "user" or "userNew" in the DongContext. xml
// Well, here we will implement AOP and print out what we actually did *_*
Object rtnInstance = rtnClass. newInstance ();
// Here is the most important sentence, the essence of reflection
// Have you seen this? The Dynamic proxy is included in our Dong, and the user code is not changed at all.
InvocationHandler handler = new EventHandler (rtnInstance );
Object rtnInProxy = Proxy. newProxyInstance (
RtnInstance. getClass (). getClassLoader (),
RtnInstance. getClass (). getInterfaces (),
Handler );
// Implement dynamic proxy
// Do you remember we kicked out rtnInstance directly? This time, we kicked out the rtnInstance agent.
Return rtnInProxy;
} Catch (Exception e ){
System. err. println (e );
}
Return tmpBean;
}
}