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.
ExampleInterface that requires proxy
public interface IHello { public void sayHello(); }
public class HelloImpl implements IHello { public void sayHello() { System.out.println(“Hello World…”); } }
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; } }
public class Main { public static void main(String[] args) { ProxyHandler proxy = new ProxyHandler(new HelloImpl()); IHello hello = (IHello) proxy.proxyInstance(); hello.sayHello(); } }
Proxy source code analysis
newProxyInstance() 方法
Omitted code that doesn’t care
public static Object newProxyInstance(ClassLoader loader, Class c){ }
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!