Reputation: 1247
I'm struggling to use an element as parameter in my code.
For my Hibernate API calls I need to specify which class the query result has to me mapped. Instead of making many small methods which are fairly simmilar I want to DRY it out.
I've got this code here:
private void selectAllFrom(MyClass myclass) {
CriteriaQuery<MyClass> query = builder.createQuery(Myclass.class);
}
Instead I want to have the MyClass-Class as a generic parameter and use the method like this:
private void selectAllFrom(Class<T> any) {
CriteriaQuery<Class<T>> query = builder.createQuery(Class<T>.class)
}
// usage:
// selectAllFrom(MyClass.class)
How can this be done in Java?
Upvotes: 1
Views: 217
Reputation: 2313
This should work. Note that you must use T
when referencing a type, and any
when referencing the Class<?>
value required by createQuery
and other methods.
private <T> void selectAllFrom(Class<T> any) {
CriteriaQuery<T> query = builder.createQuery(any)
}
Upvotes: 4