[Object null judgment + time zone issue + carry of date in string format + serialization and deserialization]

1. Object judgment

public static boolean isEmpty(Object value) {
    
    
    if (value == null) {
    
    
        return true;
    } else if (value instanceof String) {
    
    
        return ((String)value).length() == 0;
    } else if (value instanceof Collection) {
    
    
        return ((Collection)value).size() == 0;
    } else if (value instanceof Map) {
    
    
        return ((Map)value).size() == 0;
    } else if (value instanceof String[]) {
    
    
        return ((String[])((String[])value)).length == 0;
    } else {
    
    
        return false;
    }
}

instanceof: a reserved keyword in Java. Its function is to test whether the object on its left is an instance of the class on its right and return a boolean data type. instanceof is generally used for object type coercion. instanceof is a binary operator in Java, with objects on the left and classes on the right.
Instances of a class include its own instance, as well as instances of all direct or indirect subclasses
instanceof. The explicitly declared type on the left and the operand on the right must be of the same type or have an inheritance relationship, which means they need to be in the same inheritance tree, otherwise it will compile mistake

usage:

  1. The object instance on the left cannot be a basic data type
  2. The object instance on the left and the class on the right are not in the same inheritance tree
  3. When comparing null with any type using instanceof, it will always be false.

2. Time zone issues

Problem: When inserting data into the database, it was found that some data were inserted at the wrong time. The
final cause was: daylight saving time problem.
Solution: Add time zone restrictions when declaring the date field, and the time zone is the Shanghai time zone.

@JsonFormat(pattern = "yyyyMMdd", timezone = "Asia/Shanghai")

3. Carry of date in string format

Rounded up by minutes:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
LocalDateTime localDateTime = LocalDateTime.parse(String.valueOf(i), dtf);
LocalDateTime plus = localDateTime.plus(i, ChronoUnit.MINUTES);
String format = dtf.format(plus);
int i = Integer.parseInt(format);

4. A brief discussion on calling third-party jar packages

The third-party jar package is just a tool class and its dependencies will not be very strong.
Take bold breakpoints to find the cause of the error.
At that time, a null pointer exception occurred during the call, and I didn't look at the call carefully.
A null pointer exception like this means that there is no value assigned somewhere. Look carefully, then assign a value, and that's it! ! !

The issued code is the realization code at that time:

package cn.hsa.bis;

import cn.hsa.bis.api.psnDataSyncTencent.dto.PsnBasInfoQueryDTO;
import cn.hsa.hsaf.core.gateway.*;
import cn.hsa.hsaf.tencent.gateway.RioApiCaller;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

public class TencentTest {
    
    

    public static void main(String[] args) {
    
    
// 因为是一个测试类,已经不能调用配置文件和依赖注入的类了,所以需要的东西要自己new,并且参数也要自己赋值;这是需要看调用的第3方jar包看到的。
        RioApiCaller rioApiCaller = new RioApiCaller();
        rioApiCaller.setPaasid("hsa_bic");
        rioApiCaller.setToken("T6t2Q7i9rPukJhuPc6ogvXt2qNe5LWfB");
        rioApiCaller.setGatewayUrl("http://10.97.240.206:80/ebus");
        rioApiCaller.setName("rioApiCaller");
        rioApiCaller.init();  // 当时没有调用这个初始化方法,一直报空指针异常。

        PsnBasInfoQueryDTO psnBasInfoQueryDTO = new PsnBasInfoQueryDTO();
        psnBasInfoQueryDTO.setPsnMgtcode(args[0]);
        String jsonData = JSON.toJSONString(psnBasInfoQueryDTO);
        ContentBody cb = new ContentBody(jsonData);
        HttpParameters hp = HttpParameters.newBuilder()
                .api("/hsa-bic-nation-psnbasinfoservicee-queryPsnInfoByQueryDTO/")
                .version("1.0.0")
                .method("POST")
                .contentBody(cb)
                .build();
        Map<String, String> extMap = new HashMap<String, String>();
        String result = null;
        try {
    
    
            result = rioApiCaller.invoke(hp, extMap);
        } catch (ApiCallerException e) {
    
    
            e.printStackTrace();
        }
        System.out.println(result);
    }
}

5. Serialization and deserialization

1. Definition:
Serialization: The process of converting Java objects into byte sequences (binary).
Deserialization: The process of restoring a sequence of bytes into a Java object.

2. Function:
The most important function of serialization is to ensure the integrity and deliverability of objects when transferring and saving objects. The object is converted into an ordered stream of bytes for transmission over the network or for saving in a local file.

The most important role of deserialization: reconstruct the object through deserialization based on the object status and description information saved in the byte stream.

Summary: The core function is to save and reconstruct the object state (the core point of the whole process is the object state and description information saved in the byte stream)

Note: Serialization is the process of converting object state into a format that can be maintained or transmitted. The opposite of serialization is deserialization, which converts a stream into an object. These two processes combine to easily store and transfer data. JSON is the format used for interface data exchange.

json/xml data transmission:
Before data transmission (also called network transmission), Java objects are serialized into json/xml files through the serialization tool class.
After data transmission (also called network transmission), the json/xml file is deserialized into an object in the corresponding language.

3. Why serialization and deserialization are needed
? We know that when two processes communicate remotely, they can send various types of data to each other, including text, pictures, audio, video, etc., and these data will be in the form of binary sequences. transmitted over the network.

So when two Java processes communicate, can object transfer between processes be achieved? The answer is yes! How to do it? This requires Java serialization and deserialization!

In other words, on the one hand, the sender needs to convert the Java object into a byte sequence and then transmit it on the network; on the other hand, the receiver needs to recover the Java object from the byte sequence.

When we understand why Java serialization and deserialization are needed, we naturally think about the benefits of Java serialization. The first advantage is that it achieves the persistence of data. Through serialization, the data can be permanently saved to the hard disk (usually stored in a file). The second is that serialization is used to achieve remote communication, that is, the bytes of the object are transmitted over the network. sequence.

Generally speaking, it can be boiled down to the following points:

  1. Permanently save the object's byte sequence to the hard disk, usually in a file; (persistent object)
  2. A sequence of bytes that transmits an object over the network. (Network transfer object)
  3. Pass objects between processes through serialization;

4. In Java, if an object wants to be serialized, it must implement one of the following two interfaces:

Serializable interface
If an object wants to be serialized, its class must implement this interface or its sub-interface.
All attributes of this object (including private attributes and objects referenced by it) can be serialized and deserialized to save and transfer. Fields that do not want to be serialized can be modified using transient.
Since the Serializable object is constructed entirely based on the binary bits it stores, no constructor is called, so the Serializable class does not need a default constructor. However, when the parent class of the Serializable class does not implement the Serializable interface, the deserialization process will Call the default constructor of the parent class, so the parent class must have a default constructor, otherwise an exception will be thrown.
Although it is simple and convenient to use the transient keyword to prevent serialization, the attribute modified by it is completely isolated from the serialization mechanism, resulting in the value of the attribute being unable to be obtained during deserialization. Adding the writeObject() method and readObject() method to the Java class can control how to serialize each attribute, and even not serialize some attributes at all or encrypt and serialize some attributes.

Externalizable interface
It is a subclass of Serializable interface. The writeExternal() and readExternal() methods that users need to implement are used to determine how to serialize and deserialize.
Because the serialization and deserialization methods need to be implemented by yourself, you can specify which properties to serialize, and transient is not valid here.
When deserializing an Externalizable object, the parameterless constructor of the class will be called first, which is different from the default deserialization method. If you delete the constructor without parameters of the class, or set the access permission of the constructor to private, default or protected level, a java.io.InvalidException: no valid constructor exception will be thrown, so the Externalizable object must have a default constructor Function, and must be public.
Usage:
You only want to hide one attribute, such as the password pwd of the user object user. If you use Externalizable and write every attribute except pwd in the writeExternal() method, this seems troublesome. You can use the Serializable interface and add it in This can be achieved by adding transient in front of the attribute pwd to be hidden. If you want to define a lot of special processing, you can use Externalizable.
The writeObject() method and readObject() method in Serializable can implement custom serialization, and the writeExternal() and readExternal() methods in Externalizable can also be used. What are the similarities and differences between them?
There are two methods, readExternal() and writeExternal(). Except for the method signatures of the two methods and the method signatures of the readObject() and writeObject() methods, their method bodies are exactly the same.
It should be pointed out that when using the Externalizable mechanism to deserialize the object, the program will use the public parameterless constructor to create an instance, and then execute the readExternal() method to deserialize, so the serialization class that implements Externalizable must provide public No-argument construction.
Although implementing the Externalizable interface can bring certain performance improvements, implementing the Externalizable interface leads to an increase in programming complexity. Therefore, most of the time, serialization is implemented by implementing the Serializable interface.

5. Serialization version----serialVersionUID field
During the serialization process, the serialized version can be controlled. This field is the serialVersionUID field in the serialized object.

For an object data, during the deserialization process, if the serialVersionUID in the serialization string is different from the current object value, the deserialization fails, otherwise it succeeds.
If serialVersionUID is not generated explicitly, the system will automatically generate one. The generated inputs include: class name, class and its attribute modifiers, interfaces and interface order, attributes, static initialization, and constructors. Changes in any item will cause serialVersionUID to change.
Changes in attributes will cause changes in the automatically generated serialVersionUID. For example, for object A, we generate serialized S(A), and then modify the attributes of A. At this time, the serialVersionUID of A changes. During deserialization, the serialVersionUID of S(A) is different from that of A and cannot be deserialized. An error of inconsistent serial number version will be reported.
In order to avoid this problem, the general system will require classes that implement the serialiable interface to explicitly generate a serialVersionUID. There are two uses for explicitly defining
serialVersionUID:
when you want different versions of a class to be compatible with serialization, you need to ensure that different versions of the class have the same serialVersionUID;
when you do not want different versions of the class to be compatible with serialization, you need to ensure that different versions of the class have Different serialVersionUID.
If we keep the serialVersionUID consistent, during deserialization, the default value null (the default value of int is 0) will be filled in for the newly added fields, and the reduced fields will be ignored directly.

Guess you like

Origin blog.csdn.net/m0_46459413/article/details/128802417