1.定义一个father类来限制泛型的上限
class father {
}
2.定义两个子类继承father模拟真实业务中的情况
// 表格一返回值bean
class son1 extends father {
private String name;
private Integer level;
public son1(String name, Integer level) {
this.name = name;
this.level = level;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
@Override
public String toString() {
return "son1{" +
"name='" + name + '\'' +
", level=" + level +
'}';
}
}
// 表格二返回值bean
class son2 extends father {
private String name;
private Integer level;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
@Override
public String toString() {
return "son1{" +
"name='" + name + '\'' +
", level=" + level +
'}';
}
}
3.利用反射机制写一个根据传入的对象和传入的对象的属性名来获取对应get方法对应值的方法
public static Object getObject(Object obj, String filedName) {
Object res = null;
try {
String methodName = "get" + filedName.substring(0, 1).toUpperCase(Locale.ROOT) + filedName.substring(1);
Method method = obj.getClass().getMethod(methodName);
res = method.invoke(obj);
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
4.【关键】定义泛型方法来限制泛型的上限,使我们传入的参数必须继承于father类
参数一:需要排序的集合
参数二:需要参与排序的字段
参数三:需要排序的集合的泛型的class对象
public static <T extends father> List<T> sort(List<T> list, String filedType, Class<T> clz) {
List<T> collect = list.stream().map(clz::cast).sorted((o1, o2) -> {
String s1 = getObject(o1, filedType).toString();
String s2 = getObject(o2, filedType).toString();
return s1.compareTo(s2);
}).collect(Collectors.toList());
return collect;
}
5.测试 泛型为son1的集合,根据name字段排序
public static void main(String[] args) {
ArrayList<son1> son1s = new ArrayList<>();
son1 son1 = new son1("abc", 2);
son1 son2 = new son1("bbb", 1);
son1s.add(son1);
son1s.add(son2);
List<com.bbbs.springcloud.controller.huawei.son1> resultList = sort(son1s, "name", son1.class);
resultList.forEach(System.out::println);
}
打印排序后的集合发现已经根据name进行排序