Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize java from static Agent to dynamic Agent

2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to realize java from static agent to dynamic agent". In daily operation, I believe many people have doubts about how to realize java from static agent to dynamic agent. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubt of "how to realize java from static agent to dynamic agent". Next, please follow the editor to study!

1. What is an agent?

Citing a paragraph on the Internet, the proxy pattern provides a proxy object to an object, and the proxy object controls the reference to the original object. Popularly speaking, the agency model is a common intermediary in our lives.

Let me give an example: if I want to buy a used car now, although I can find the source of the car and do a series of vehicle transfer procedures such as quality inspection, it is really a waste of my time and energy. I just want to buy a car. Why should I do so much extra work? So I buy a car through an intermediary company, and they come to find the source of the car for me and help me with the vehicle transfer process. I am just responsible for choosing the car I like and then paying for it. The figure is shown as follows:

How to implement proxy ① in 2.java. The noun of agency

Proxy object: enhanced object Target object: enhanced object

two。 Static agent

Let's assume a scenario where users are queried and log records are written before the query.

Public class UserDaoImpl {public void query () {System.out.println ("query user information");}}

In the above code, we want to enhance its function, which can be achieved by modifying the code.

Public class UserDaoImpl {public void query () {System.out.println ("log"); System.out.println ("query user information");}}

This implementation can achieve the effect, but it breaks the object-oriented opening and closing principle. And sometimes, we can not get the source code of the Dao, and there is no way to modify it. Therefore, we can consider the proxy mode to achieve.

Inherit

Write a subclass of UserDaoImpl and override the query method.

Public class ProxyUserDao extends UserDaoImpl {@ Override public void query () {System.out.println ("log"); super.query ();}}

Write tests and execute tests.

Public static void main (String [] args) {ProxyUserDao proxyUserDao = new ProxyUserDao (); proxyUserDao.query ();}

Polymerization

Both the target object and the proxy object implement the same interface. Write UserDao interface

Public interface UserDao {public void query ();}

UserDaoImpl implementation

Public class UserDaoImpl implements UserDao {public void query () {System.out.println ("query user information");}}

Write proxy classes

Public class ProxyUserDao implements UserDao {/ / target object UserDao userDao; / / pass the target object public ProxyUserDao (UserDao userDao) {this.userDao = userDao;} @ Override public void query () {System.out.println ("log"); userDao.query ();}} through the constructor

Rewrite test

ProxyUserDao proxyUserDao = new ProxyUserDao (new UserDaoImpl ()); proxyUserDao.query ()

After execution, you can also complete the agent. The above implementation is to first print log, in the execution of the query, then to implement the first execution of the query, and then print log, we have to write a proxy class, wouldn't it hurt.

Now let's assume that we want to implement multiple functional enhancements, which used to be logging, log, and we need family time to record time, so there are a variety of combinations here.

So if there are different requirements, there will be different ways of implementation, each of which has to write different agent implementation logic. A large number of java proxy classes will be written. If we look back at the way inheritance is implemented, it will be more troublesome and there will be more proxy classes.

The shortcomings and Summary of the two ways

Inheritance: too many proxy classes, more complex aggregation: there will also be a large number of proxy classes, but it is much better than inheritance.

Therefore, in uncertain situations, do not use static proxies, because a large number of proxy classes will be written to meet different needs. It's troublesome. The simulation here is only a UserDao, if there are multiple target proxy objects, then by hard-coding, it is really very irrational.

3. Dynamic agent

We can avoid the trouble of writing a large number of proxy objects through dynamic proxies.

Manual implementation of dynamic proxy

Let's first analyze the way to generate an object. Step 1: write a .java file

Step 2: compile the .java file and get the .class file. Step 3: the class recording mechanism loads the .class file and new the object.

First analysis of the first step: we write java files, we are in order not to write a lot of class code, so this method is not effective, in addition, you can also write a program to output a java file. Directly paste the source code below:

Public class ProxyUtil {/ * content-> string * .java io * .class * .new reflection-"class * @ return * / public static Object newInstance (Object target) {Object proxy=null; Class targetInf = target.getClass (). GetInterfaces () [0]; Method methods [] = targetInf.getDeclaredMethods (); String line="\ n "; String tab ="\ t " String infName = targetInf.getSimpleName (); String content = ""; / / assemble agent class code String packageContent = "package com.google;" + line; String importContent = "import" + targetInf.getName () + ";" + line; String clazzFirstLineContent = "public class $Proxy implements" + infName+ "{" + line; String filedContent = tab+ "private" + infName+ "target;" + line String constructorContent = tab+ "public $Proxy (" + infName+ "target) {" + line+tab+ tab+ "this.target = target;" + line+tab+ "}" + line; String methodContent = "; for (Method method: methods) {String returnTypeName = method.getReturnType (). GetSimpleName (); String methodName = method.getName () / / Sting.class String.class Class args [] = method.getParameterTypes (); String argsContent = ""; String paramsContent= ""; int flag = 0; for (Class arg: args) {String temp = arg.getSimpleName () / / String / / String p0je Sting p1, argsContent+=temp+ "p" + flag+ ","; paramsContent+= "p" + flag+ ","; flag++;} if (argsContent.length () > 0) {argsContent=argsContent.substring (0recoery argsContent.lastIndexOf (",")-1) ParamsContent=paramsContent.substring (0paramsContent.lastIndexOf (",")-1);} / / Agent printing log log function (here is written dead) methodContent+=tab+ "public" + returnTypeName+ "+ methodName+" ("+ argsContent+") {"+ line + tab+tab+" System.out.println (\ "log\") "+ line + tab+tab+" target. "+ methodName+" ("+ paramsContent+"); "+ line + tab+"} "+ line;} / / the code string in class content=packageContent+importContent+clazzFirstLineContent+filedContent+constructorContent+methodContent+"} "; File file = new File (" / / $Proxy.java "); try {if (! file.exists ()) {file.createNewFile () } / / write content to java file FileWriter fw = new FileWriter (file); fw.write (content); fw.flush (); fw.close (); / / compile java file java--- > class JavaCompiler compiler = ToolProvider.getSystemJavaCompiler (); StandardJavaFileManager fileMgr = compiler.getStandardFileManager (null, null, null) Iterable units = fileMgr.getJavaFileObjects (file); JavaCompiler.CompilationTask t = compiler.getTask (null, fileMgr, null, units); t.call (); fileMgr.close (); / / Class loading URL [] urls = new URL [] {new URL ("file:D:\\")}; URLClassLoader urlClassLoader = new URLClassLoader (urls) Class clazz = urlClassLoader.loadClass ("com.google.$Proxy"); / / get constructor Constructor constructor = clazz.getConstructor (targetInf); / reflection create instance proxy = constructor.newInstance (target);} catch (Exception e) {e.printStackTrace ();} return proxy;}}

The above is the written agent tool class, will achieve the generation of java proxy files, java compilation, loading, reflection to create instances. Calling newInstance returns the proxy object. But here the agency function is written to death.

Write test classes. And execute

UserDao o = (UserDao) ProxyUtil.newInstance (new UserDaoImpl ()); o.query ()

The corresponding file has been generated under the directory

View the generated proxy class code

The log printed by the console enables the method to be printed with the log.

To implement proxies for other target objects, we just need to call newInstance to pass in the target object.

For example, we need to add log printing to the order OrderDao query order

/ / order Dao interface public interface OrderDao {public void query ();} / order Dao API implements the target object public class OrderDaoImpl implements OrderDao {public void query () {System.out.println ("query order");}} / / Test function public static void main (String [] args) {OrderDao o = (OrderDao) ProxyUtil.newInstance (new OrderDaoImpl ()); o.query ();}

Only need to test and query the log to achieve the agent of the order interface.

Through dynamic proxies, we can achieve proxies for different target objects without writing proxy objects manually. Enhanced the extensibility of the code. The bottom layer of ps:java also has a utility class proxy for dynamic proxies. His implementation principle is the same.

At this point, the study of "how to realize java from static agent to dynamic agent" is over. I hope to be able to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report