我已经奋斗了相当长一段时间,并查找了一些资源,试图理解如何使用泛型来实现我想要实现的目标,但一直无法找到提供我想要实现的目标的示例需要。
一些示例包括使用 Supplier接口(interface)或建议拥有一个泛型类,然后实例化它。
我想要实现的是指定我希望方法返回的类型,同时在方法中实例化相同类型并将其添加到列表中,然后返回该列表。
提前致谢。将不胜感激任何帮助
public List<Doctor> queryDoctor() {
Statement statement = null;
ResultSet results;
try {
statement = connection.createStatement();
results = statement.executeQuery("SELECT * FROM " + TABLE_DOCTOR);
List<Doctor> doctors = new ArrayList<>();
while (results.next()) {
Doctor doctor = new Doctor();
doctor.setId(results.getInt(1));
doctor.setUserName(results.getString(2));
doctor.setPassword(results.getString(3));
doctor.setPassword_salt(results.getString(4));
doctor.setRole(results.getInt(5));
doctors.add(doctor);
}
return doctors;
} catch (SQLException e) {
System.out.println("Query failed: " + e.getMessage());
return null;
} finally {
try {
if (statement != null) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
最佳答案
您需要传入Function<ResultSet, T>
:
<T> List<T> queryDoctor(Function<ResultSet, T> fn)
并在循环中使用它:
doctors.add(fn.apply(results));
此函数将创建适当的具体类型:
List<Doctor> doctors = queryDoctor(results -> {
Doctor doctor = new Doctor();
doctor.setId(results.getInt(1));
doctor.setUserName(results.getString(2));
doctor.setPassword(results.getString(3));
doctor.setPassword_salt(results.getString(4));
doctor.setRole(results.getInt(5));
return doctor;
});
或
List<Nurse> nurses = queryDoctor(results -> {
Nurse nurse = new Nurse();
// ...
return nurse;
});
关于java - 泛型方法在实例化方法中传递的泛型类型时返回列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50095289/