In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Java dynamic agent how to start the most simple InvocationHandler, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.
On the Internet, there are very advanced articles about the concepts of Java dynamic agent, Proxy and InvocationHandler. In fact, these concepts are not that complicated. Now let's use the simplest example to understand what InvocationHandler is. It is worth mentioning that InvocationHandler is widely used in the implementation of the Spring framework, which means that we have eaten through InvocationHandler, which lays a solid foundation for future Spring source code learning.
Develop an interface that contains two methods that can say "hello" or "good-bye" to a specified person.
Public interface IHello {void sayHello (String name); void sayGoogBye (String name);}
Create a simple class that implements the IHello interface.
Public class Helloimplements implements IHello {@ Override public void sayHello (String name) {System.out.println ("Hello" + name);} @ Override public void sayGoogBye (String name) {System.out.println (name+ "GoodBye!");}}
Consumption of this implementation class is nothing special so far.
Now suppose we receive this request: the boss requires that every time the implementation class greets someone, the details of the greeting must be recorded in a log file. For simplicity, we print the following line before greeting to simulate the logging action.
System.out.println ("logging before greeting...")
It's not easy, you might say. Directly modify the corresponding method of Helloimplements and insert this line of log into the corresponding method.
However, the boss's requirement is that you are not allowed to modify the original Helloimplements class. In a real-world scenario, Helloimplements may be provided by a third-party jar package, and we have no way to modify the code.
You might say that we can use the proxy pattern in the design pattern, that is, create a new Java class as the proxy class, also implement the IHello interface, and then pass an instance of the Helloimplements class into the proxy class. Although we are not allowed to modify the Helloimplements code, we can write the logging code in the proxy class. The complete code is as follows:
Public class StaticProxy implements IHello {private IHello iHello; public void setImpl (IHello impl) {this.iHello = impl;} @ Overridepublic void sayHello (String name) {System.out.println ("logging before greeting..."); iHello.sayHello (name);} @ Overridepublic void sayGoogBye (String name) {System.out.println ("logging before greeting..."); iHello.sayGoogBye (name) } static public void main (String [] arg) {Helloimplements hello = new Helloimplements (); StaticProxy proxy = new StaticProxy (); proxy.setImpl (hello); proxy.sayHello ("Jerry");}}
This approach can meet the requirements:
Let's see how to achieve the same effect with InvocationHandler.
InvocationHandler is a standard interface provided by JDK. Look at the following code: import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;public class DynaProxyHello implements InvocationHandler {private Object delegate; public Object bind (Object delegate) {this.delegate = delegate; return Proxy.newProxyInstance (this.delegate.getClass (). GetClassLoader (), this.delegate.getClass (). GetInterfaces (), this) } public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {Object result = null; try {System.out.println ("logging before greeting..."); / / JVM executes the original method (reflection mechanism) result = method.invoke (this.delegate, args) through this statement } catch (Exception e) {e.printStackTrace ();} return result;}
The bind method in the above code is very similar to the setImpl method of my previous proxy class StaticProxy, except that the input parameter type of this bind method is more generic. The code for logging is written in the method invoke.
See how to use:
Static public void main (String [] arg) {DynaProxyHello helloproxy = new DynaProxyHello (); Helloimplements hello = new Helloimplements (); IHello ihello = (IHello) helloproxy.bind (hello); ihello.sayHello ("Jerry");}
The implementation effect is exactly the same as the solution of StaticProxy.
Let's debug it first. When the bind method executes, the method Proxy.newProxyInstance is called and an instance of the Helloimplements class is passed in.
We observe the ihello variable returned by the line IHello ihello = (IHello) helloproxy.bind (hello) in the debugger. Although its static type is IHello, note that looking at its actual type in the debugger is not an instance of Helloimplements, but something that JVM has done for us, including the line of logging code we handwritten in the invoke method. The ihello type is $Proxy0.
When the sayHello method of the variable processed by JVM is called, JVM automatically transfers the call to DynaProxyHello.invoke:
So, in the invoke method, our handwritten logging code is executed, and then the original sayHello code is executed through Java reflection.
Some friends may ask, your InvocationHandler looks more complicated than static proxy StaticProxy. What's the advantage?
Suppose the boss's needs change again, and different logging strategies are used in calling greetings and saying goodbye.
Take a look at how elegantly implemented with InvocationHandler:
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.