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

Definition of MyBatis reflection and dynamic proxy

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces "the definition of MyBatis reflection and dynamic proxy". In daily operation, I believe that many people have doubts about the definition of MyBatis reflection and dynamic proxy. The editor has consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "the definition of MyBatis reflection and dynamic proxy". Next, please follow the editor to study!

Understanding reflection and dynamic proxy reflection

First, take a look at the official website's definition of reflection:

You can obtain the fields, methods, constructors and other information of the currently loaded class through java code, and use reflected fields, methods and constructors to operate within the security limit.

To put it simply, you can get member information for each type of the program at run time. The types of objects defined in the program are determined at compile time, while reflection can dynamically create objects and access or invoke their members.

Dynamic agent

The so-called agency is that one person or organization acts on behalf of another person or organization. there are mainly three roles: the visitor, the agent and the principal. The visitor interacts with the principal through the agent, adding some of his own processing in the middle.

The so-called dynamic proxy means that the proxy class does not need to be defined at compile time, but is created at run time, which is the key: create the proxy class at run time.

Class object

The Class class is a real class that exists in the java.lang package to represent runtime type information. The Class object represents the type information of the custom class. For example, if you create a User class, JVM will create a Class object corresponding to User and store the type information related to the User class. The object is stored in the jvm heap as an interface to access the User type information in the method area.

When using a custom class, it will first check whether the Class object of the class has been loaded, if not, the default class loader will first look for the .class file based on the class name, and the Class object will be loaded into memory.

You can get the Class object in three ways:

Use the forName static method of the Class class

Get the class of an object directly

Call the getClass () method of an object

The Class object is the basis for reflection and provides a way to get class information, as described later.

Functions provided by reflection

The java reflection framework mainly provides the following:

Determine the class to which the object belongs at run time

Create objects at run time

Get the member variables, methods, parents, interfaces and other information contained in the class at run time

Call the method of an object at run time

The following examples illustrate the relevant functions

Create an instance:

/ / get the Class object corresponding to String Class c = User.class;// get the constructor Constructor constructor = c.getConstructor (String.class) of the String class with one String parameter; / / create an instance User user = (User) constructor.newInstance ("calm") according to the constructor

Get method:

/ / returns all methods declared by the class or interface, including private but not inherited methods public Method [] getDeclaredMethods () throws SecurityException// all public methods, including inherited methods public Method [] getMethods () throws SecurityException// returns a specific method, the first parameter is the method name, followed by the method parameter corresponding to the Class object public Method getMethod (String name, Class...) ParameterTypes)

Call method:

Class userClass=User.class;Object obj = userClass.newInstance (); Method method = klass.getMethod ("addRole", String.class); method.invoke (obj, "Super Admin"); JDK dynamic Agent

JDK itself provides the implementation of dynamic proxy, which requires the principal to implement the interface.

Public static Object newProxyInstance (ClassLoader loader,Class [] interfaces,InvocationHandler h)

The first parameter is the classloader, the second parameter is the list of interfaces implemented by the agent, and the third parameter is the object that implements the InvocationHandler interface.

InvocationHandler is an interface that standardizes the method of executing the principal, adding common processing code before and after the method is executed. The generated dynamic proxy class contains an InvocationHandler property that triggers a call to the invoke method when the corresponding method is called.

Public class JDKProxy implements InvocationHandler {private Object targetObject;// proxied object public Object newProxy (Object targetObject) {this.targetObject = targetObject; return Proxy.newProxyInstance (targetObject.getClass (). GetClassLoader (), targetObject.getClass (). GetInterfaces (), this);} public Object invoke (Object proxy, Method method, Object [] args) / / invoke method throws Throwable {Object ret = null Ret = method.invoke (targetObject, args); return ret;}}

Test the code:

JDKProxy jdkProxy=new JDKProxy (); UserService userService = (UserService) jdkProxy.newProxy (new UserServiceImp ()); userService.addRole ("Super Admin")

The basic principle of the JDK dynamic proxy is to create a new class with the incoming interface based on the defined rules.

CGLIB dynamic agent

The JDK dynamic proxy requires that there must be an interface. The CGLIB (Code Generate Library) dynamic proxy does not have this requirement. It is achieved by creating a subclass of the proxied class and then modifying the code using the ASM bytecode library.

Public class CGLibProxy implements MethodInterceptor {private Object targetObject; / / proxied object public Object createProxyObject (Object obj) {this.targetObject = obj; Enhancer enhancer = new Enhancer (); enhancer.setSuperclass (obj.getClass ()); enhancer.setCallback (this); Object proxyObj = enhancer.create (); return proxyObj } public Object intercept (Object proxy, Method method, Object [] args, MethodProxy methodProxy) throws Throwable {Object obj = null; obj = method.invoke (targetObject, args); return obj;}}

Test the code:

CGLibProxy cgLibProxy=new CGLibProxy (); UserService userService = (UserService) cgLibProxy.newProxy (new UserServiceImp ()); userService.addRole ("Super Admin"); at this point, the study of "definition of MyBatis reflection and dynamic proxy" is over, hoping 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

Development

Wechat

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

12
Report