How to use the Eclise extraction method, see extracting code Snippets using Eclipse as a method
After the extraction is complete, you also need to
① Change Collection.class to Target.getclass (), Target is object and can be used to delegate all objects
②proxy.newproxyinstance (target.getclass (). getClassLoader (),
Target.getclass (). Getinterfaces (),
New Invocationhander () {
Invoke (Object Proxy,method method,object[] args) {
Advice.beforemethod (method);//When we use Spring AOP, we write only beforemethod similar cross-function implementations
Object retval= Proxy.invoke (Target,args);
Advice.aftermethod (method);//When we use Spring AOP, we write only the implementation of aftermethod similar cross-functional methods
return retVal;
}
}
)
I passed the eclipse-encapsulated black box.
Private static Object GetProxy (Final object target,final Advice Advice) {object proxy3= (Collection) Proxy.newproxyinstance (Target.getclass (). getClassLoader (), Target.getclass (). Getinterfaces (), New Invocationhandler () {@Overridepublic object Invoke (Object proxy, Method method, object[] args) throws Throwable {/*long be Gintime=system.currenttimemillis (); Object Retval=method.invoke (target, args); Long endtime= System.currenttimemillis (); System.out.println (Method.getname () + "Execution Time" + (Endtime-begintime) + "millisecond"), return Retval;*/advice.beforemethod (method Object Retval=method.invoke (target, args); Advice.aftermethod (method); return retVal;}}); return proxy3;}
So call the black box
Final ArrayList target=new ArrayList ()///class variable Collection Proxy3 = (Collection) getproxy (target,new myadvice ());
I wrote the Myadvice, where advice would be defined by spring, and there would be various methods of location, such as Aftermethod,beforemethod, after throwing, around
Package Com.itcast.day3;import Java.lang.reflect.method;public class Myadvice implements Advice {long begintime=0;@ Overridepublic void Beforemethod (method) {System.out.println ("to Preach Wisdom Podcast learning ..."); begintime= System.currenttimemillis ();} @Overridepublic void Aftermethod (method) {System.out.println ("Graduation work from Preach Intelligence podcast ..."); Long endtime= System.currenttimemillis (); System.out.println (Method.getname () + "Execution Time" + (Endtime-begintime) + "millisecond");}}
When you use Spring AOP in the future, you only do two things,
① determining target object targets
② Write Myadvice (in fact, to implement the spring provided by the advice interface Beforemethod, Aftermethod method)
Do something spring AOP has done, encapsulating the JDK dynamic agent into a black box