我有两个类(Admin, Patient)都扩展了User类和一个通用类(UserDao<T>
)
我想在UserDao<T>
中写一些方法,只对Admin或Patient类中的一个可见。
public class UserDao<T extends User> {
private Connection connection;
public UserDao(Connection connection) {
this.connection = connection;
}
public <T extends Patient> boolean addPrescription(T t, Prescription prescription) {
boolean isAdded = false;
int patientId = t.getId();
ArrayList<Item> items = prescription.getItems();
ItemDao itemDao = new ItemDao(connection);
try {
PreparedStatement ps = connection.prepareStatement(Constants.ADD_PATIENT_ID_PRESCRIPTIONS_QUERY);
ps.setInt(1, patientId);
int result = ps.executeUpdate();
if (result == 1) {
for (var item : items) {
isAdded = itemDao.addItem(item);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return isAdded;
}
}
但是在主类中,我可以看到两种类型
的方法UserDao<Patient> patientUserDao = new UserDao<>(DbConnection.getConnection());
UserDao<Admin> adminUserDao = new UserDao<>(DbConnection.getConnection());
Admin admin = new Admin();
Patient patient = new Patient();
Prescription prescription = new Prescription();
patientUserDao.addPrescription(patient, prescription);
adminUserDao.addPrescription(patient,prescription);
在Java中没有办法做到这一点。泛型类型的方法必须支持该泛型类型的所有值。
你能做的最接近的事情是编写静态帮助程序接受受限制的类型:
static boolean addPrescription(UserDao<Patient> patient, Prescription prescription) {
...
}