Requirements: Timed task scanning, reflecting calls the target object, but the method's argument transmission is not fixed.
Solution 1: Save the method parameters into a JSON string, then deserialize JSON into an object, and then reflect the call
The target method is like this:
CommandResp sendXXX(BaseCommandApiDTO<XXX> baseCommandApiDTO);
Method 1: FastJson
Class mainBody = (()); ParameterizedTypeImpl parameterizedType = new ParameterizedTypeImpl(new Type[]{mainBody}, null, ); Object obj = ((), parameterizedType); CommandResp resp = (serviceObj, methodName, obj);
Method 2: Jackson
public class ObjectMapperHolder { private static final ObjectMapper objectMapper = new ObjectMapper(); public static ObjectMapper getObjectMapper() { (new Jdk8Module()); (new JavaTimeModule()); return objectMapper; } } ObjectMapper mapper = (); JavaType javaType = ().constructParametricType(, mainBody); Object obj = ((), javaType); CommandResp resp = (serviceObj, methodName, obj);
In practice, it was found that these two methods could easily lead to OOM
Solution 2: Save the parameter object directly into the database
The corresponding fields of the database are set to BLOB type (MEDIUMBLOB is set here), and the corresponding java field type is byte[]
// Write to the objectByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); (baseCommandApiDTO); (); byte[] data = (); // Read the objectObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(())); Object obj = ();
Finally, optimization suggestions:
1. Try not to store json strings in the database. If you have to store them, it is recommended to set the field type to json, which can save space. Because you can't control the length of the json string, the length setting is a problem. In addition, json deserialization takes up more memory.
2. It is recommended to save a separate association table in fields with large lengths (such as blob type).
This is the end of this article about JSON string deserialization dynamic generics. For more related content on JSON string deserialization, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!