泛型是jdk5之后出来的一种新特性,使用泛型可以增强代码的可读性和稳定性。
编译器可以检测泛型,并且通过泛型参数可以指定传入参数。
泛型如何使用?
泛型的应用类别分为泛型类、泛型接口、泛型方法
泛型类比如mybatis plus中的IserviceImpl,通过泛型来标记对应实现类对应的类,
泛型接口也可以参考MP中的Iservice,仍然通过泛型来标记对应实现的接口,
还有泛型方法。
在项目中使用泛型比如通用返回接口success<T>,再比如各种工具类,
1.通用返回接口包含code、message、data,其中data使用泛型,可以返回不同类的数据
public class ApiResponse<T> {
private int code;
private String message;
private T data;
public static <T> ApiResponse<T> success(T data) {
ApiResponse<T> r = new ApiResponse<>();
r.code = 0; r.message = "OK"; r.data = data;
return r;
}
public static <T> ApiResponse<T> error(int code, String msg) {
ApiResponse<T> r = new ApiResponse<>();
r.code = code; r.message = msg;
return r;
}
// getters/setters...
}
2.工具类的实现,比如实现不同类的拼接
为什么说泛型提升了代码的稳定性?
因为在jdk5版本之前,如List的使用没有泛型,如果添加的过程添加了两个不同类,编译时不会报错,而运行时会出现类转换异常,但是在使用了泛型之后,将报错提前到了编译时期,从而从根本上避免了类转换异常。