1. The agent's writing, is more troublesome, writes the native agent, is also a bored and is easy to omit the thing. Write a simple proxy class that can be used to refer to errors as well.
1 Packagecn;2 3 ImportJava.lang.reflect.InvocationHandler;4 ImportJava.lang.reflect.Method;5 ImportJava.lang.reflect.Proxy;6 7 /**8 * The base of the proxy class, you must first set the object (must be the interface object assignment implementation Class), otherwise the obtained proxy object will be null pointer. 9 * @authorJxlysTen * One */ A Public classProxybaseImplementsInvocationhandler { - PrivateObject obj; - the Publicproxybase () { - } - - Publicproxybase (Object obj) { + This. obj =obj; - } + A PublicObject getobj () { at returnobj; - } - - Public voidsetobj (Object obj) { - This. obj =obj; - } in - /** to * Get proxy object + * - * @paramT the * @return * */ $ Public<T> T GetProxy (class<t>t) {Panax Notoginseng returngetObject (T, GetProxy ()); - } the + /** A * Get proxy object the */ + PublicObject GetProxy () { - returnObj! =NULL? Proxy.newproxyinstance (Obj.getclass (). getClassLoader (), Obj.getclass (). Getinterfaces (), This) :NULL; $ } $ - //Object Strong Turn -@SuppressWarnings ("Unchecked") the Public<T> T GetObject (class<t>T, Object obj) { - returnObj! =NULL? (T) obj:NULL;Wuyi } the - Public voidbeforeaction () { Wu } - About Public voidafteraction () { $ } - - PublicObject Invoke (Object proxy, Method method, object[] args)throwsThrowable { - beforeaction (); AObject invoke =method.invoke (obj, args); + afteraction (); the returninvoke; - } $}
The call is as follows:
1 InterfaceA {2 Public voidsay ();3 }4 5 classBImplementsA {6 7 Public voidsay () {8System.out.print ("Love");9 }Ten } One A Public classTestmain { - - Public Static voidMain (string[] args) { theA = new B (); -A.say ();//non-agent -Proxybase Pbu =NewProxybase (a) { - Public voidbeforeaction () { +System.out.print ("I"); - } + A Public voidafteraction () { atA = GetObject (A.class, Getobj ()); -System.out.print ("you!"); - } - }; -A = Pbu.getproxy (A.class); -PBU =NULL;//This step is not important, also can not. in A.say ();//agent can also be implemented in an inherited way. - } to}
Java Proxy Base Class 1.0