Implementation and principle of JDK dynamic Proxy
Author: two Green
E-mail: xtfggef@gmail.com Weibo: HTTP://WEIBO.COM/XTFGGEF
Dynamic proxies, which sound very tall technology, are widely used in Java, especially in the framework of Hibernate and spring, where dynamic proxies are implemented in AOP, privilege control, and transaction management. JDK itself has the implementation of dynamic proxy technology, but a slight limitation, that is, the proxy class must implement an interface, otherwise the JDK can not use the dynamic agent, so if not meet the conditions, you can only use another more flexible, more powerful dynamic agent technology--cglib. Spring will automatically switch between the JDK's agents and cglib, and we can force spring to use Cglib. The following is a brief introduction to the knowledge points of the dynamic agent in turn.
Let's take a look at an example:
Create a new interface, Userservice.java, with only one method add ().
Package com.adam.java.basic;
Public interface UserService {public
abstract void Add ();
}
Build a implementation class for this interface Userserviceimpl.java
Package com.adam.java.basic;
public class Userserviceimpl implements UserService {
@Override public
Void Add () {
System.out.println ("- ---add-----");
}
Build an agent processing class Myinvocationhandler.java
Package com.adam.java.basic;
Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Method;
Import Java.lang.reflect.Proxy;
public class Myinvocationhandler implements Invocationhandler {
private Object target;
Public Myinvocationhandler (Object target) {
super ();
This.target = target;
}
Public Object GetProxy () {return
proxy.newproxyinstance (Thread.CurrentThread ()
. Getcontextclassloader () , Target.getclass (). Getinterfaces (), this
);
@Override Public
object Invoke (Object proxy, Method method, object[] args)
throws Throwable {
SYSTEM.OUT.PRINTLN ("-----Before-----");
Object result = Method.invoke (target, args);
SYSTEM.OUT.PRINTLN ("-----After-----");
return result;
}
Test class
Package com.adam.java.basic;
public class Dynamicproxytest {public
static void Main (string[] args) {
UserService userservice = new UserService Impl ();
Myinvocationhandler Invocationhandler = new Myinvocationhandler (
userservice);
UserService proxy = (userservice) invocationhandler.getproxy ();
Proxy.add ();
}
Execute the test class and get the following output:
-----before-----
-----Add-----
-----after-----
Here, we should think of something:
1. Who and how the proxy object is generated.
2. How the Invoke method is invoked.
3. What is the correspondence between the invoke and add methods?
4. What the generated proxy object looks like.
With these questions, let's look at the source code. First of all, our entrance is the GetProxy () method in the test class above, we follow it and look at this method:
Public Object GetProxy () {return
proxy.newproxyinstance (Thread.CurrentThread ()
. Getcontextclassloader (), Target.getclass (). Getinterfaces (), this);
That is, the JDK's dynamic proxy is implemented through a class called Proxy, and we continue to follow in to see the Newproxyinstance () method of the proxy class. Let's take a look at the JDK's notes:
/**
* Returns An instance's a proxy class for the specified interfaces
* This dispatches method invocations to th E specified invocation
* handler.
*
* <p>{@code proxy.newproxyinstance} throws
* {@code illegalargumentexception} for the same reasons that< c6/>* {@code Proxy.getproxyclass} does.
*
* @param Loader the class loader to define the proxy class
* @param interfaces The list of interfaces For the proxy class
* to implement
* @param h the invocation handler to dispatch method invocations to
* @return a proxy instance with the specified invocation handler of a
* proxy class so is defined B Y the specified class loader
* And that implements the specified interfaces
According to JDK annotations, we know that the Newproxyinstance method will eventually return an instance of the class that implements the specified interface, with three parameters: ClassLoader, the specified interface, and our own defined Invocationhandler class. I'm going to pick up a few key pieces of code and see how the instance objects of this proxy class are generated.
class<?> cl = GETPROXYCLASS0 (loader, intfs);
...
Final constructor<?> cons = Cl.getconstructor (constructorparams);
...
Return cons.newinstance (New object[]{h});
Interested students can look at the source of the JDK, the current version I use is JDK1.8.25, the implementation of each version may be different, but basically consistent, please study the source of the students to pay attention to this point. The code above shows that the proxy class is first obtained by Getproxyclass, and then the constructor is taken by C1.getconstructor (), and the last step, Returns an instance of this new proxy class by cons.newinstance, note: When calling newinstance, the incoming parameter is H, the Invocationhandler class that we define well, remember this step first, we know the reason why here.
In fact these three code, the core is this getproxyclass method, the other two lines of Java reflection Application, and our current interest point does not matter, so we continue to study this getproxyclass method. This method, the annotation is very simple, as follows:
* * Look up or generate the designated proxy class.
* *
class<?> cl = getProxyClass0 (loader, intfs);
is to generate this key proxy class, we follow up to see.
private static class<?> GetProxyClass0 (ClassLoader loader,
class<?> ... interfaces) {
if ( Interfaces.length > 65535) {
throw new IllegalArgumentException ("Interface limit Exceeded");
If the proxy class defined by the given loader implementing
//The given interfaces, this'll exists return The cached copy;
Otherwise, it would create the proxy class via the Proxyclassfactory return
proxyclasscache.get (loader, interfaces);
}
Here is a cache, first check from the cache, if there is, direct return, does not exist on the newly created. In this get method, we see the following code:
Object subkey = Objects.requirenonnull (Subkeyfactory.apply (key, parameter));
Apply () is mentioned here as the internal class of the proxy class proxyclassfactory a method of implementing its interface, which is implemented as follows:
Public class<?> Apply (ClassLoader loader, class<?>[] interfaces) {
map<class<?>, boolean> Interfaceset = new identityhashmap<> (interfaces.length);
for (class<?> intf:interfaces) {
/
* * Verify the Class loader resolves the name of this
* Interfa Ce to the same Class object.
* *
class<?> interfaceclass = null;
try {
Interfaceclass = Class.forName (Intf.getname (), false, loader);
} catch (ClassNotFoundException e) {
}
if (Interfaceclass!= intf) {
throw new IllegalArgumentException (
intf + "isn't" visible from class load Er ");
} ...
When I see Class.forName (), I think most people will laugh, and finally see the familiar method, yes. This place is to load the specified interface, since it is the generated class, that must have the corresponding class byte code, we continue to look down:
* * Generate the specified proxy class.
* *
byte[] proxyclassfile = Proxygenerator.generateproxyclass (
proxyname, interfaces, accessflags);
try {return
defineClass0 (loader, proxyname,
proxyclassfile, 0, proxyclassfile.length);
This code is the final return value of the GETPROXYCLASS0 () method that uses Proxygenerator to generate the final proxy class for us. So let's take a look at the first four questions:
1. Who and how the proxy object is generated.
2. How the Invoke method is invoked.
3. What is the correspondence between the invoke and add methods?
4. What the generated proxy object looks like. For the first question, I think the answer is clear, I repeat the idea: by the proxy class GetProxyClass0 () method to generate the target proxy class, and then get the class of construction methods, and finally through the reflection of the Newinstance method, generate proxy class instance object.
Next, we look at the other three methods, I would like to start from the fourth, because the above generated bytecode code, then we can imitate this step, we generate bytecode file to see, so, I use the following code, generated this final proxy class.
Package com.adam.java.basic;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Sun.misc.ProxyGenerator;
public class Dynamicproxytest {public
static void Main (string[] args) {
UserService userservice = new UserService Impl ();
Myinvocationhandler Invocationhandler = new Myinvocationhandler (
userservice);
UserService proxy = (userservice) invocationhandler.getproxy ();
Proxy.add ();
String Path = "c:/$Proxy 0.class";
byte[] Classfile = Proxygenerator.generateproxyclass ("$Proxy 0",
UserServiceImpl.class.getInterfaces ());
FileOutputStream out = null;
try {out
= new FileOutputStream (path);
Out.write (classfile);
Out.flush ();
} catch (Exception e) {
e.printstacktrace ();
} finally {
try {
out.close ();
} catch ( IOException e) {
e.printstacktrace ();}}}
The Proxy.add () in the above test method, where the Add () method, is not the Add () method of the original UserService, but the Add () method of the newly generated proxy class, we will generate the $ Proxy0.class file opened with Jd-gui, I removed some code, add () method is as follows:
Public final void Add ()
throws
{
try
{
This.h.invoke (this, M3, null);
return;
}
catch (error| RuntimeException localerror)
{
throw localerror;
}
catch (Throwable localthrowable)
{
throw new undeclaredthrowableexception (localthrowable);
}
}
The core is this.h.invoke (this. m3, null); what's H here? Let's take a look at the class name of this class:
Public final class $Proxy 0 extends Proxy implements UserService
It is not difficult to find that the newly generated class inherits the proxy class to implement the UserService method, and this userservice is the interface we specify, so here we can basically conclude that the dynamic proxy for JDK, the new proxy class that is generated, inherits the proxy base class, The class that implements the incoming interface. So what exactly is this h? Let's take a look at this new proxy class and see the constructor:
Public $Proxy 0 (Invocationhandler Paraminvocationhandler)
throws
{
super (Paraminvocationhandler);
}
A Invocationhandler type parameter is passed in the constructor, and when we see this, we should think of the previous line of code:
Return cons.newinstance (New object[]{h});
This is the last sentence of the Newinstance method, the incoming H, which is the h that is used here, the instance of the Myinvocationhandler class that we originally defined ourselves. So, we find that the last call to the Add () method actually calls the Myinvocationhandler invoke () method. Let's look at this method again, look for the meaning of M3, continue to see the source code of the proxy class:
Static
{
Try
{
m1 = Class.forName ("Java.lang.Object"). GetMethod ("equals", new class[] { Class.forName ("Java.lang.Object")});
M2 = Class.forName ("Java.lang.Object"). GetMethod ("ToString", new Class[0]);
M3 = Class.forName ("Com.adam.java.basic.UserService"). GetMethod ("Add", new class[0);
M0 = Class.forName ("Java.lang.Object"). GetMethod ("Hashcode", new class[0);
return;
}
The discovery of surprise, originally this M3, is the original interface of Add () method, see here, what still do not understand. I think the 2,3,4 problem should be solved. Let's go ahead and look at the Invoke () method in the original Myinvocationhandler:
@Override Public
object Invoke (Object proxy, Method method, object[] args)
throws Throwable {
SYSTEM.OUT.PRINTLN ("-----Before-----");
Object result = Method.invoke (target, args);
SYSTEM.OUT.PRINTLN ("-----After-----");
return result;
}
M3 is going to be passed in the method, so, why first output before, after the output after, to here is not all understand it. This is the JDK dynamic agent the whole process, it is not difficult.
Finally, let me summarize the process of the JDK dynamic proxy:
1. Define an interface in which you need to implement the method and write the actual implementation class.
2. Define a Invocationhandler class, implement the Invocationhandler interface, override the Invoke () method, and add the GetProxy () method.
Summarize the dynamic proxy implementation process:
1. Generate the proxy class through GETPROXYCLASS0 ().
2. Generates an instance object of the proxy class through Proxy.newproxyinstance (), passing in an instance of the Invocationhandler type when the object is created.
3. The method that invokes the new instance, that is, add () in this example, the Invoke () method in the original Invocationhandler class.
Well, wrote so much, also should end, thanks Bo friend Rejoy an article, let me have a reference. At the same time welcome everyone to ask a discussion, if there is a problem, please leave a message, I will take time to reply. Related code has been uploaded to the Baidu network disk, download the address.
Contact Method:
Email: xtfggef@gmail.com
Micro Blog: HTTP://WEIBO.COM/XTFGGEF
References: http://rejoy.iteye.com/blog/1627405