编写基础工具类时,尽量使用泛型;
//使用泛型类
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class DataListPageInfo<T> {
int page;
int pageSize;
int totalCount;
List<T> items = new ArrayList<>();
}
@Component
public class RedisTemplateService {
private static final Logger LOGGER = LoggerFactory.getLogger(RedisTemplateService.class);
@Resource
private RedisTemplate redisTemplate;
private String getKey(String key, Object... params) {
if (params == null || params.length <= 0) {
return key;
}
return String.format(key, params);
}
//这里使用了泛型方法
public <T> T getFromJsonCache(Class<T> type, String keyPrefix, Object... params) {
try {
String ret = getString(keyPrefix, params);
return JSON.parseObject(ret, type);
} catch (Exception e) {
LOGGER.error("json parse error, type={},keyPrefix={},params={}", type, keyPrefix, params, e);
}
return null;
}
……
}