Home > Java > javaTutorial > Analysis on the principle of dynamic proxy in Java

Analysis on the principle of dynamic proxy in Java

黄舟
Release: 2017-10-16 10:17:49
Original
1919 people have browsed it

This article mainly introduces relevant information on the analysis of Java dynamic proxy principles. I hope this article can help everyone to master the principles of dynamic proxy. Friends in need can refer to it

Java Analysis of dynamic proxy principle

Summary

The interception function of AOP is implemented by the dynamic proxy in java. To put it bluntly, it is to add aspect logic on the basis of the target class to generate an enhanced target class (the aspect logic is executed either before the target class function is executed, or after the target class function is executed, or when the target class function throws an exception. Spring The dynamic proxy in is implemented using Cglib. What we analyze here is the dynamic proxy implementation mechanism in JDK.

Let’s quickly understand the dynamic proxy implementation in JDK through examples.

Example

Interface that requires proxy

public interface IHello { 
public void sayHello(); 
}
Copy after login

Class that requires proxy

public class HelloImpl implements IHello { 
public void sayHello() { 
System.out.println(“Hello World…”); 
} 
}
Copy after login

Calling processor implementation class

public class ProxyHandler implements InvocationHandler { 
private Object target; 
public ProxyHandler(Object target) { 
this.target = target; 
} 
public Object proxyInstance() { 
return Proxy.newProxyInstance(target.getClass().getClassLoader(), 
target.getClass().getInterfaces(), this); 
} 
public Object invoke(Object proxy, Method method, Object[] args) 
throws Throwable { 
System.out.println(“aspect before … “); 
Object result = method.invoke(this.target, args); 
System.out.println(“aspect after … “); 
return result; 
} 
}
Copy after login

Test class entry

##
public class Main { 
public static void main(String[] args) { 
ProxyHandler proxy = new ProxyHandler(new HelloImpl()); 
IHello hello = (IHello) proxy.proxyInstance(); 
hello.sayHello(); 
} 
}
Copy after login

Proxy source code analysis

newProxyInstance() 方法
Copy after login

Omitted code that doesn’t care

public static Object newProxyInstance(ClassLoader loader, Class c){

}
Copy after login

The above is the detailed content of Analysis on the principle of dynamic proxy in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template