java利用泛型,写通用方法

来源:互联网 发布:电脑网络接口灯不亮 编辑:程序博客网 时间:2024/05/16 09:30

使用场景:有一个po类型, 假设类型名为:user。 其中必定有getId()方法。 现在从数据库中查出了一组user。  List<User>, 现在要只提取它们的id,到List<Long>中

我们可以写 个for循环,遍历 提取到 List<Long> idList

又有一个po类型,假设类型名为:student。同样也有getId()方法。又有同样的需要,从一组List<Student>中提取  List<Long> idList, 又要写for循环提取。

这样就出现了 类似重复的代码。


现在通过 java 泛型方法,写通用方法提取 List<Long> idList

泛型写法:

public static <T> List<Long> fetchId(List<T> itemList) {
List<Long> idList = new ArrayList<Long>();
if (itemList.isEmpty()) {
idList.add(0L);
return idList;
}
try {
Method m = itemList.get(0).getClass().getDeclaredMethod("getId");
for (T item : itemList) {
Long id = StringUtil.getNullLong(m.invoke(item));
idList.add(id);
}
return idList;
} catch (Exception e) {
e.printStackTrace();
return idList;
}
}


0 0