我有以下方法Person通過 Id回傳一個物件:
private Person getPersonById(String client) {
Person output = null;
EntityManager entityManager = null;
try {
entityManager = entityManagement.createEntityManager(client);
output = entityManager.find(Person.class, id);
} catch (Exception e) {
// handle
} finally {
entityManagement.closeEntityManager(client, entityManager);
}
return output;
}
有沒有辦法讓這個方法更通用,以便我可以傳入其他物件型別,例如
Place, Cost?請注意,這些不繼承相同的超類。
例如,我應該Person.class作為方法引數等傳遞嗎?
uj5u.com熱心網友回復:
如果你想傳入一個類物件并使你的方法通用,你可以這樣做:
private <E> E getObjectById(String client, Class<E> cls) {
E output = null;
EntityManager entityManager = null;
try {
entityManager = entityManagement.createEntityManager(client);
output = entityManager.find(cls, id);
} catch (Exception e) {
// handle
} finally {
entityManagement.closeEntityManager(client, entityManager);
}
return output;
}
如果您Person.class作為cls引數傳遞,它將等效于您的原始代碼。
假設entityManager.find它將接受任何類并嘗試回傳該類的實體。
如果entityManager.find對其接受的類的特征有一些限制,則需要在泛型型別引數中指定它們<E>。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/389717.html
上一篇:過濾流會改變它的通配符邊界嗎?
下一篇:使用建構式擴展泛型型別
