Reputation: 3082
I have a class MyApi
with a generic method get()
as below.
public class MyApi {
public <T> T get(Class<T> clazz) {
// business logic to create and return instance of T
return null;
}
}
Which is good so far. But in a few cases, I have to pass a class and will get different class Object in return.
How can I make the same method as generic without introducing a new parameter to same method, for example:
public class MyApi {
public <T, E> E get(Class<T> clazz1, Class<E> clazz2) {
// business logic to create and return instance of E
return null;
}
}
Eg: To avoid joins on NoSQL I have a Employee
class and its materialized view class EmployeeByDepartment
. For above api I pass EmployeeByDepartment
and expecting Employee
object as a response.
Upvotes: 1
Views: 1943
Reputation:
Your method is trying to do too much, namely, it's trying to resolve the correct class, and then create an object based on that class.
Let's split this up into two methods, one for resolving the correct class, and one for instantiating the object itself.
First, we find the correct class to create:
private Class getCorrectClass(Class<?> clazz) {
if(clazz.equals(someClass.class)){
return someOtherClass.class;
}
// whatever business logic that
// will return proper class
return clazz;
}
Then, we create it:
public <T> T get(Class<?> clazz) {
Class clazzy = getCorrectClass(clazz);
// business logic to create and return instance of T
return (T) clazzy.newInstance(); //or however you decide how to init it
}
Now, whenever you call get, it'll resolve the correct class, then proceed to initialize the proper object.
Upvotes: 1
Reputation: 425003
If you re-phrase your requirements, you want to return a generic type, but don't care about the parameter type.
This will allow T
to be inferred:
public <T> T get(Class<?> clazz) {
// business logic to create and return instance of T
return null;
}
Using classes in your example, you could then code:
Employee employee = myApi.get(EmployeeByDepartment.class)
You'll probably need an unchecked cast inside the get()
method, but so what.
Upvotes: 3