泛型作为java的一个基础特性,从jdk5开始引入,在jdk中有广泛的应用,比如List接口。
一些常用的泛型类型变量:
E:元素(Element),多用于java集合框架
K:关键字(Key)
N:数字(Number)
T:类型(Type)
V:值(Value)
泛型的意义在于:
1、适用于多种数据类型执行相同的代码;
2、泛型中类型在使用时指定,不需要强制类型转换(类型安全,编译器会检查类型);
泛型主要有方法泛型、类泛型、接口泛型;
泛型方法:
private static <T> T genericAdd(T a, T b) {
System.out.println(a + "+" + b + "="+a+b);
return a;
}
泛型类:
public class GenericTest<T> {
private T data;
public static void main(String[] args) {
GenericTest<String> str = new GenericTest<>();
str.setData("str");
System.out.println(str.getData());
GenericTest<Integer> integerGenericTest = new GenericTest<>();
integerGenericTest.setData(6);
System.out.println(integerGenericTest.getData());
}
}
泛型接口:
public interface GenericTestInteface<T> {
T getData();
}
-----------------分割线-------------
下面从项目中的场景,描述下泛型的应用。
项目中多个接口的报文结构一样的,只不过不同的接口接收不同的对象,如下图报文所示,itemList中的对象不一样;
{
"type": "typeValue",
"createTime": "2020-12-3 13:31:35",
"itemList": [
{
"stationCode": "工位编码",
"status": "状态",
...
}
]
}
{
"type": "typeValue2",
"createTime": "2020-12-3 13:31:35",
"itemList": [
{
"productionLineCode": "产线编码",
"productionLineName": "产线名称",
...
}
]
}
...
这个时候我们接收报文的对象就可以抽象成一个公共的对象,itemList中的对象使用泛型;
public class BaseEntity<T> {
private String type;
private Date createTime;
private List<T> itemList;
}
在controller接收的时候,需要根据具体的业务用具体的类(***Entity)接收处理;
@PostMapping(value = "/sync/info")
public ResultMap syncInfo(@Validated @RequestBody BaseEntity<***Entity> baseEntity) {
return ResultMap.success(***Service.doSyncInfo(baseEntity));
}
以上就是泛型在项目中的一次应用。