1. JDK can generate a proxy for the instance that implements the interface. Therefore, first create an interface.
// Interface person
Package cn.edu. HLD;
Public interface person
{
Public void Info ();
Public void run ();
}
2. To implement dynamic proxy later, an implementation class of the person interface is provided.
// Class personimpl. Java
Package cn.edu. HLD;
Public class personimpl implements person
{
Public void Info ()
{
// Todo auto-generated method stub
System. Out. println ("I am thtwin ");
}
Public void run ()
{
// Todo auto-generated method stub
System. Out. println ("I want to run faster! ");
}
}
3. Implement the core interceptor class when a method is called before or after the corresponding interceptor method is executed. As to which object to intercept, it must be reflected through subsequent operations.
// Personintercepter. Java
Package cn.edu. HLD;
Public class personintercepter
{
Public void Method1 ()
{
System. Out. println ("method_1 is executed! ");
}
Public void method2 ()
{
System. Out. println ("method_2 is executed! ");
}
}
4. To let the interceptor know the target object to be intercepted and the method to be executed, create a class that implements the interface invocationhandler In the JDK reflection system.
// Proxyhandler. Java
Package cn.edu. HLD;
Import java. Lang. Reflect. invocationhandler;
Import java. Lang. Reflect. method;
Public class proxyhandler implements invocationhandler
{
Private object target;
Private personintercepter Pi = new personintercepter ();
Public object invoke (Object proxy, method, object [] ARGs)
Throws throwable
{
Object result = NULL;
If (method. getname (). Equals ("info "))
{
Pi. Method1 ();
Result = method. Invoke (target, argS );
Pi. method2 ();
}
Else
{
Result = method. Invoke (target, argS );
}
Return result;
}
Public void settarget (object target)
{
This.tar get = target;
}
}
5. To generate a proxy object based on the target object, you should also create a proxy factory.
// Myproxyfactory. Java
Package cn.edu. HLD;
Import java. Lang. Reflect. proxy;
Public class myproxyfactory
{
Public static object getproxy (object target)
{
Proxyhandler handler = new proxyhandler ();
Handler. settarget (target );
Return proxy. newproxyinstance (personimpl. Class. getclassloader ()
, Target. getclass (). getinterfaces (), Handler );
}
}
6. Implementation of the main program.
// Testperson. Java
Package cn.edu. HLD;
Public class testperson
{
Public static void main (string ARGs [])
{
Person targetperson = new personimpl ();
Person = NULL;
Object proxy = myproxyfactory. getproxy (targetperson );
If (proxy instanceof Person)
{
Person = (person) proxy;
}
Person.info ();
Person. Run ();
}
}
7. Run the command directly in myeclipse. The result is as follows:
Method_1 is executed!
I'm thtwin.
Method_2 is executed!
I want to run faster!
96 stack Software Programming Network, http://www.96dz.com, sharing C, C ++, Java, C #. NET Programming Technology Resources, video tutorial