A simple description of the scene: monitoring the vehicle, recording the time spent on the vehicle's movement.
Now we have a vehicle interface:
Public Interface imoveable { void Move ();}
The means of transport includes a move method.
Then define a specific vehicle, taking the car as an example:
Public class Implements imoveable { @Override publicvoid Move () { // Implement Drive Try { thread.sleep (new Random (). Nextint ()); System.out.println ("car in ...."); Catch (interruptedexception e) { e.printstacktrace (); }}}
The easiest way to monitor the time it takes to move a car is to add monitoring and control to your move. But not recommended, the reasons for the details of everyone understand.
So we might need to define a proxy class that calls car's Move method in the proxy class, with the following code:
Public class Carproxy { publicvoid Move (imoveable car) { long starttime = System.currenttimemillis (); System.out.println ("car starts ...."); Car.move (); long endtime = system.currenttimemillis (); System.out.println ("Car end driving .... ") Car travel time: " + (Endtime-starttime) +" milliseconds! "); }}
If only the vehicle is monitored, the above is fully satisfied. But if we do not want to monitor the vehicle now, we need to monitor the time of the animal run, whether to create another proxy class.
This will accumulate an infinite number of proxy classes. Is there a better way to solve it?
The point has come ...
We define a proxy class for monitoring time, for monitoring processing of all time classes, using the Invocationhandler interface, the code is as follows:
Public classTimehandlerImplementsInvocationhandler { PublicTimehandler (Object target) {Super(); This. target =Target; } PrivateObject Target; /** Parameters: * Proxy Object * method is proxy object methods * Parameters of the args method * * return Value: * Return value of the object method * */@Override Publicobject Invoke (Object proxy, Method method, object[] args)throwsThrowable {LongStartTime =System.currenttimemillis (); System.out.println ("Get started ..."); Method.invoke (target); LongEndtime =System.currenttimemillis (); System.out.println ("End ..." Time: "+ (Endtime-starttime) +" milliseconds! "); return NULL; }
Write a test method to try the proxy class above and see how it works:
Public classTest {/*** JDK Dynamic Agent test class*/ Public Static voidMain (string[] args) {Car car=NewCar (); Invocationhandler h=NewTimehandler (CAR); Class<?> CLS =Car.getclass (); /*** Loader class loader * Interfaces Implementation interface * H Invocationhandler*/imoveable M=(imoveable) proxy.newproxyinstance (Cls.getclassloader (), Cls.getinterfa CES (), h); M.move (); }}
Now all want to monitor the time can use Timehandler, only need to give the agent to pass different parameters!!!
Note: With a Java dynamic proxy, an object must implement an interface.
Java Dynamic Agent