Home >Java >javaTutorial >How to implement dynamic proxy in Java anonymous inner class?
Anonymous inner classes can be used to implement dynamic proxy in Java, through the following steps: 1. Define the interface; 2. Create an anonymous inner class that implements the InvocationHandler interface; 3. Use the Proxy class to create a proxy object; 4. Call the proxy method. In practice, dynamic proxies can enhance or intercept method calls, such as recording method execution time.
How Java anonymous inner classes implement dynamic proxies
Dynamic proxies are a technology for creating object proxies at runtime , allows enhancing or intercepting object calls without modifying the target class code. Anonymous inner classes can be used to implement dynamic proxies in Java.
1. Define the interface
First, define an interface to represent the method of the target object:
interface Target { void doSomething(); }
2. Create an anonymous inner class
To create a dynamic proxy, you can use an anonymous inner class to implement InvocationHandler
Interface:
InvocationHandler handler = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // 增强或拦截方法调用 return 1; } };
3. Create a proxy object
Next, create a proxy object using the Proxy
class:
Target proxy = (Target) Proxy.newProxyInstance(Target.class.getClassLoader(), new Class[]{Target.class}, handler);
4. Call the proxy method
Now you can call the proxy object Method, thus triggering dynamic proxy behavior:
proxy.doSomething(); // 调用代理方法
Practical case
The following is a simple example of using anonymous inner classes to implement dynamic proxy:
public class Main { public static void main(String[] args) { Target target = new TargetImpl(); InvocationHandler handler = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // 增强方法调用 long startTime = System.nanoTime(); Object result = method.invoke(target, args); long endTime = System.nanoTime(); System.out.println("方法执行时间:" + (endTime - startTime) + " 纳秒"); return result; } }; Target proxy = (Target) Proxy.newProxyInstance(Target.class.getClassLoader(), new Class[]{Target.class}, handler); proxy.doSomething(); } } interface Target { void doSomething(); } class TargetImpl implements Target { @Override public void doSomething() { System.out.println("原始方法执行"); } }
In this example, the dynamic proxy acts as a proxy for the Target
interface, which performs timing enhancements before and after the original method is called.
The above is the detailed content of How to implement dynamic proxy in Java anonymous inner class?. For more information, please follow other related articles on the PHP Chinese website!