Java Dynamic Agent

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.