Reputation: 18712
I have following class:
public abstract class AbstractService<PersistenceClass extends IPersistence,
RequestClass, ResponseClass> {
public String processRequest(final String aRequestAsText)
{
[...]
final RequestClass request = mapper.readValue(aRequestAsText,
RequestClass);
[...]
}
}
The mapper.readValue invokation is normally implemented as
mapper.readValue(aRequestAsText, Request.class)
How can I code it, if the class RequestClass is a generic?
Update 1 (06.09.2013): This code seems to work:
public class GenericTypeBindigsFinder implements IGenericTypeBindigsFinder {
@SuppressWarnings("rawtypes")
@Override
public List<Class> getGenericTypes(final Class aClass) {
final List<Class> result = new LinkedList<Class>();
final ParameterizedType gen = (ParameterizedType) aClass.getGenericSuperclass();
final Type [] types = gen.getActualTypeArguments();
for (int i = 0; i < types.length; i++) {
if (types[i] instanceof Class)
{
final Class clazz = (Class)types[i];
result.add(clazz);
}
}
return result;
}
}
You can find the corresponding unit test here.
Upvotes: 0
Views: 181
Reputation: 10895
So you want to access the generic types bound in AbstractService. You can do it via reflection. See the example code here:
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
public class GenericClass extends GenericSuper<String, Integer> {
public GenericClass() {
ParameterizedType gen = (ParameterizedType) getClass().getGenericSuperclass();
TypeVariable<?> typeVars[] = getClass().getSuperclass().getTypeParameters();
Type [] types = gen.getActualTypeArguments();
for (int i = 0; i < typeVars.length; i++) {
System.out.println("Generic parameter " + typeVars[i] +
" is bound to " + types[i]);
}
}
public static void main(String[] args) {
new GenericClass();
}
}
class GenericSuper<X, Y> {};
Output is:
Generic parameter X is bound to class java.lang.String
Generic parameter Y is bound to class java.lang.Integer
You can cast types[i]
to Class.
For a much more sophisticated solution, see getTypeArguments(...).
Upvotes: 1
Reputation: 946
Try to pass object
or an interface
preferably to the method, then you can get the class of it with the getClass()
method or maybe instanceof
.
Upvotes: 2