我有以下课程:
@Data
public class PagedSchoolDto {
private final Integer count;
private final Map<String, List<School>> content;
private final String pagingState;
private final Boolean hasNext;
public PagedSchoolDto(final Slice<School> slice) {
this.content = slice.getContent().stream().collect(
Collectors.groupingBy(School::getId, () -> new TreeMap<>(new UUIDComparator()), Collectors.toList()));
this.count = slice.getContent().size();
this.hasNext = slice.hasNext();
this.pagingState = getPagingState(slice);
}
@Nullable
private static String getPagingState(final Slice<School> slice) {
if (slice.hasNext()) {
CassandraPageRequest pageRequest = (CassandraPageRequest) slice.nextPageable();
return pageRequest.getPagingState().toString();
} else {
return null;
}
}
}
现在,我想让我的代码变得通用,以便我可以将此类用于其他对象类型,如下所示:
@Data
public class PagedDto<T> {
private final Integer count;
private final Map<String, List<T>> content;
private final String pagingState;
private final Boolean hasNext;
public PagedDto(final Slice<T> slice) {
this.content = slice.getContent().stream().collect(
Collectors.groupingBy(<T>::getId, () -> new TreeMap<>(new UUIDComparator()), Collectors.toList()));
this.count = slice.getContent().size();
this.hasNext = slice.hasNext();
this.pagingState = getPagingState(slice);
}
@Nullable
private static <T> String getPagingState(final Slice<T> slice) {
if (slice.hasNext()) {
CassandraPageRequest pageRequest = (CassandraPageRequest) slice.nextPageable();
return pageRequest.getPagingState().toString();
} else {
return null;
}
}
}
我的所有类都有一个名为 ID 的属性,它是 UUID 类型,因此比较器应该可以在所有泛型类型上正常工作。问题是我不确定如何编写 Collectors.groupingBy 的函数和供应商代码,因为第二个片段给出了编译错误。
您的通用类型 T 未指定,例如不提供 getId 方法的“对象”。为了在通用代码中访问 getId,T 必须使用 getId 方法扩展接口,该方法由与 PagedDto 一起使用的任何类实现:
public interface WithId {
UUID getId();
}
public class School implements WithId {
private UUID id;
@Override
public UUID getId() {
return id;
}
public class PagedDto<T extends WithId> {
...