Java uses generic T to determine entity type and execute different business logic

1. Scene introduction

        In web development, this kind of business logic exists. Different Vo entity classes need to call the update method of the same serviceImpl. In this scenario, we can use java generics to better solve this problem and reduce unnecessary identical business logic. Iterative implementation development of methods.

ae8d4161e91d4d1795a7e7ec74d2032e.png

 2. Code implementation

        Define two classes, namely the student class and the teacher class, set the attribute id as the number, use lombok's @Data to generate getter and setter methods, and create a common method private static <T> void print(T entiy), where < T> means using generics for programming, otherwise an error will be reported in subsequent type judgments. The specific case implementation is as follows.

import lombok.Data;

/**
 * @author Liwei
 * @date 2023/2/23 17:23
 * @description
 */
public class CertCATest {
    @Data
    public static class Student{
        private String id;
    }

    @Data
    public static class Teacher{
        private String id;
    }
    public static void main(String[] args) {
        Student student = new Student();
        student.setId("student");

        Teacher teacher = new Teacher();
        teacher.setId("teacher");

        print(teacher);

        print(student);

    }

    /**
     * 打印
     * @param entiy
     * @param <T>
     */
    private static <T> void print(T entiy) {
        if(entiy instanceof Teacher) {
            System.out.println("业务---我是老师");
            System.out.println(((Teacher) entiy).getId());
        } else if (entiy instanceof Student) {
            System.out.println("业务---我是学生");
            System.out.println(((Student) entiy).getId());
        }
    }
}

 3. Summary

        In addition to java generic T, what else? , I won’t go into the specific differences. Correct use of java generics can greatly speed up development efficiency and reduce code duplication. If you think you can, please give me a little love. Thank you for your support.​ 

 

Guess you like

Origin blog.csdn.net/m0_43432638/article/details/129196538