[英]how set a method invisible for special class type in generic class in java
I have two class (Admin, Patient) both extends User class and one generic class for them (UserDao <T>
)我有两个 class(管理员,患者)都扩展了用户 class 和一个通用的 class(UserDao
<T>
)
I want write some methods in UserDao <T>
that visible just for one of Admin or Patient class.我想在 UserDao
<T>
中编写一些仅对 Admin 或 Patient class 之一可见的方法。
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;
}
} }
but in Main Class I can see this method for both type但是在 Main Class 中我可以看到这两种类型的方法
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);
There is no way to do this in Java. Methods on a generic type must support all values of that generic type.在 Java 中没有办法做到这一点。泛型上的方法必须支持该泛型的所有值。
The closest thing you can do is write static helpers accepting the restricted types:您可以做的最接近的事情是编写 static 接受限制类型的助手:
static boolean addPrescription(UserDao<Patient> patient, Prescription prescription) {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.