The Java.lang.reflect package provides an interface and class to implement the proxy mechanism:
-
Invocationhandler
InvocationHandlerIs the interface that is implemented by the calling handler for the proxy instance.
-
Extends Object implements Serializable
ProxyProvides a static method for creating dynamic proxy classes and instances , or a superclass of all dynamic proxy classes created by these methods.
Java's dynamic proxy relies on interfaces, and although it is more efficient to generate, it is slower to execute, and the Java reflection mechanism itself consumes more resources than a normal invocation.
The choice given to clients in spring is the use of dynamic proxies in Java or the use of cglib third-party proxies , each with its own characteristics.
To put it simply, Java's proxy mechanism is implemented as follows:
- Create Business objects;
- Create handlers;
- Create proxy classes;
Example:
ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Proxy;/*** Created by lay on 21/02/2018.*/ Public classProxydemo { Public Static voidMain (string[] args) {//creating a Proxied objectFooservice Fooservice =NewFooserviceimpl (); //implementing handlers for proxied objectsInvocationhandler handler =NewMyinvocationhandler (Fooservice); //returns the proxy objectFooservice Fooserviceproxy =(Fooservice) proxy.newproxyinstance (Fooservice.getclass (). getClassLoader (), Fooservice.getclass (). Getinterfaces (), handler); //Proxy Object Invocation methodFooserviceproxy.getdata (); }}
/***/Publicinterface fooservice {void GetData ();}
/***/Publicclassimplements fooservice { @Override publicvoid getData () { System.out.println ("called the Fooservice Implementation class method---GetData ..."); }}
ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method;/*** Implement JDK Dynamic Agent interface * Created by lay on 21/02/2018.*/ Public classMyinvocationhandlerImplementsInvocationhandler {PrivateObject Target; PublicMyinvocationhandler (Object target) { This. target =Target; } @Override PublicObject Invoke (Object proxy, Method method, object[] args)throwsthrowable {System.out.println ("Before the execution ..."); Object result=Method.invoke (Target,args); System.out.println ("After execution ..."); returnresult; }}
Java Implementation AOP facets (dynamic proxy)