1. Define Annotations
Importjava.lang.annotation.Documented;ImportJava.lang.annotation.ElementType;Importjava.lang.annotation.Retention;ImportJava.lang.annotation.RetentionPolicy;ImportJava.lang.annotation.Target, @Documented @retention (retentionpolicy.runtime) @Target (Elementtype.method) Public@Interfacemethodannotation {String name ()default"Default Annotation Name"; String URL ()default"Default.com";}
2. Information class using annotations
Public Interface iproxytest { @MethodAnnotation () publicvoid testmethodannotation (); @MethodAnnotation (Name= "Amazon", url= "z.cn") publicvoid Testmethodannotationwithvalue ();}
3. Implement the interface
Public class Implements iproxytest { publicvoid testmethodannotation () { System.out.println (" Useannotion->testmethodannotation "); } Public void Testmethodannotationwithvalue () { System.out.println ("useannotion-> Testmethodannotationwithvalue ");} }
4. Dynamic proxy class implementation and main test
ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Proxy; Public classLogproxyImplementsInvocationhandler {Private Static intCount = 0; PrivateObject Target; PrivateLogproxy () {}Private StaticObject getinstance (Object o) {logproxy LP=NewLogproxy (); Lp.target=o; Object result=proxy.newproxyinstance (O.getclass (). getClassLoader (), O. GetClass (). Getinterfaces (), LP);//Proxy Object returnresult; } @Override Publicobject Invoke (Object proxy, Method method, object[] args)throwsThrowable {if(Method.isannotationpresent (methodannotation.class) {methodannotation annotation=method. getannotation (methodannotation.class); Count++;//Usage Scenario: Count the number of interfaces that can be degraded within the performance range System.out.println ("Execute Method" + method.getname () + ":" +count); } Object obj=Method.invoke (target, args); returnobj; } Public Static voidMain (string[] args) {iproxytest ua=NewProxytestimpl (); Iproxytest LP=(iproxytest) logproxy.getinstance (UA); Lp.testmethodannotation (); Lp.testmethodannotationwithvalue (); }}
Java Annotations and proxy implementations