Previously, I wrote a method for a specific entity class called Address
and here's the code :
private List<AddLuceneWork> buildAddLuceneWorks(List<Address> addresses) {
List<AddLuceneWork> addWorks = new LinkedList<>();
session = em.unwrap(Session.class);
searchIntegrator = ContextHelper.getSearchintegrator(session);
entityIndexBinding = searchIntegrator
.getIndexBindings()
.get(Address.class); // specific type
// ...
return addWorks;
}
And now, I want to make the input to be generic, so that no matter what entity can be processed. But I didn't use generic type before and I don't know how to use it properly :
private <T> List<AddLuceneWork> buildAddLuceneWorks(List<T> entities) {
List<AddLuceneWork> addWorks = new LinkedList<>();
session = em.unwrap(Session.class);
searchIntegrator = ContextHelper.getSearchintegrator(session);
entityIndexBinding = searchIntegrator
.getIndexBindings()
.get(Address.class); // <- how to change it to generic ?
// ...
return addWorks;
}
I tried the following, but they didn't work :
.get(T);
.get(T.class);
.get(clazz.getClass());
where Class<T> clazz = null;
Due to Type Erasure your code at Runtime
is actually
private List buildAddLuceneWorks(List entities) {
Such that it cannot work, you need to add an additional parameter of type Class
to provide the expected type explicitly like this:
private <T> List<AddLuceneWork> buildAddLuceneWorks(List<T> entities, Class<T> clazz) {
Then get(Address.class)
will then be get(clazz)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments