This is the 30th day of my participation in the Gwen Challenge.More article challenges


preface

Didn’t think it’s in the past 30 days, wanting more, straight-tempered themselves insist on down, originally written technical articles, in order to push myself grow and learn, keeping and stopping, one not careful to slack off, and they can never understand is ok, rarely consider the feelings of the readers, the idea of later slowly changed, north drift years have to leave some traces of their existence, In the future will also slowly precipitation some technical knowledge points and usually used in the project of the technical tools design mode and other efforts to write some good articles helpful to everyone, the road of technology, not to advance is to retreat, mutual encourage!

Last time we introduced the concept and function of reflection in Java, as well as some preliminary use methods of reflection, today we will look at the actual use of reflection in the project scenario;

Reflection usage scenario

Java reflection mechanism is rarely used in the usual business development process, but it is widely used in the construction of some basic frameworks. We can find the source code, in Spring, Mybatis such framework, a large number of reflection operations are used;

When writing a frame by hand

When you’re building a framework, sometimes you don’t know what class you need, what methods you need, and what properties that class has. For example, after querying the database, the data is reflected into objects. You can imagine we often use a variety of database interaction framework, now in the XML configuration files, for example, defined the result set to accept a database object for the com. Wechat. Wechatservice. Entity. The User according to the configuration, we put this set of data, Convert to objects in the configuration;

Simple code implementation:

package com.wechat.wechatservice.controller; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang3.StringUtils; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Set; /** * TODO ** @author taoze * @version 1.0 * @date 6/29/21 2:29pm */ public class MyDataSql {/** * pretend we have an XML */ public static String getXmlData() { return "com.wechat.wechatservice.entity.User"; } /** * public static String getDataFromDatabase() {return "{\" age \ ": \" 30 \ ", \ "name \" : \ "zhang SAN \", \ "sex \" : \ "m \} \ n"; } public static void main(String[] args) throws Exception { Class useClass = Class.forName(getXmlData()); Object needObj = useClass.newInstance(); JSONObject datas = JSON.parseObject(getDataFromDatabase()); Set<String> keys = datas.keySet(); for (String key : keys) { Method md = useClass.getMethod("set" + StringUtils.capitalize(key), String.class); md.invoke(needObj, datas.get(key)); } System.out.println(needObj); }}Copy the code

Running results:

Java’s reflection and dynamic proxy mechanisms implement Spring’s AOP.

Interfaces and implementation classes for interfaces

public interface UserService { void addUser(); void updateUser(); void deleteUser(); } public class UserServiceImpl implements UserService { @Override public void addUser() { System.out.println("add user"); } @Override public void updateUser() { System.out.println("update user"); } @Override public void deleteUser() { System.out.println("delete user"); }}Copy the code

Cut class MyAspect

public class MyAspect { public void befor() { System.out.println("befor..." ); } public void after() { System.out.println("after..." ); }}Copy the code

Proxy class used to get the target class

import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; Public class MyBeanFactroy {public static UserService CreateUserService() {// Final UserService UserService = new UserServiceImpl(); // Final MyAspect MyAspect = new MyAspect(); / / the third UserService proxyService = (UserService) Proxy. NewProxyInstance (MyBeanFactroy. Class. GetClassLoader (), new Class[] { UserService.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method Method, Object[] args) throws Throwable {// step 5 myasp.befor (); Object obj = method.invoke(userService, args); // myaspect.after (); return obj; }}); return proxyService; }}Copy the code

Ok! This is the end of today’s article, I hope it can be helpful to you, there are wrong places I hope you can put forward, grow together;

Neat makes for great code, and there’s only so much detail