Invocationhandler is used to implement proxy.
If you do not use the invocationhandler interface to implement proxy, we write the code as follows:
Define an interface:
-
Java code
-
interface Greet{ void sayHello(String name); void goodBye();}
Implement this interface:
-
Java code
-
class GreetImpl implements Greet{ public void sayHello(String name) { System.out.println("Hello " + name); } public void goodBye() { System.out.println("Good bye."); }}
Implement a proxy class
-
Java code
-
Public class simpleproxy implements greet {private greet = NULL; simpleproxy (GREET greet) {This. greet = greet;} public void sayhello (string name) {system. out. println ("-- before method sayhello"); greet. sayhello (name); system. out. println ("-- after method sayhello");} public void goodbye () {system. out. println ("-- before method goodbye"); greet. goodbye (); system. out. println ("-- after method goodbye");}/*** @ Param ARGs */public static void main (string [] ARGs) {greet = new simpleproxy (New greetimpl (); // generate the proxy greet. sayhello ("Walter"); greet. goodbye ();}}
The proxy is actually nothing. Let's see if the invocationhandler interface is implemented,
How can we implement proxy.
You still need to implement the original greet interface.
The implementation of the interface is greetimpl.
-
Java code
-
Import Java. lang. reflect. invocationtargetexception; import Java. lang. reflect. method; public class debugproxy implements Java. lang. reflect. invocationhandler {private object OBJ; public static object newinstance (Object OBJ) {return Java. lang. reflect. proxy. newproxyinstance (obj. getclass (). getclassloader (), obj. getclass (). getinterfaces (), new debugproxy (OBJ);} private debugproxy (Object OBJ) {// greet interface: greetimpl this. OBJ = OBJ;} // method M: method used by the volume // object [] ARGs: number of objects to be written into the method public object invoke (Object proxy, method M, object [] ARGs) throws throwable {object result; try {// custom processing system. out. println ("-- before method" + M. getname (); // use the method result = m in greetimpl. invoke (OBJ, argS);} catch (invocationtargetexception e) {Throw E. gettargetexception ();} catch (exception e) {Throw new runtimeexception ("unexpected invocation exception:" + E. getmessage ();} finally {system. out. println ("-- after method" + M. getname ();} return result;}/*** @ Param ARGs */public static void main (string [] ARGs) {greet TMP = new greetimpl (); greet greet = (GREET) debugproxy. newinstance (TMP); // The generated greet and TMP have the same hashcode greet. sayhello ("Walter"); greet. goodbye ();}}