Reputation: 1201
Why does calling val.isValid(request)
gives a compile error Required: type capture of ?, provided: T
?
How can I fix the error?
public class RequestValidator implements IRequestValidator{
private Map<Class<?>, IValidator<?>> validatorMap;
public RequestValidator() {
validatorMap = new HashMap<>();
}
@Override
public <T> void registerValidator(Class<T> clazz, IValidator<T> validator) {
validatorMap.put(clazz, validator);
}
@Override
public <T> boolean validate(T request) {
if (validatorMap.containsKey(request.getClass())) {
IValidator<?> val = validatorMap.get(request.getClass());
return val.isValid(request);
}
return true;
}
}
IValidator
interface:
public interface IValidator<T> {
boolean isValid(T t);
}
Upvotes: 11
Views: 22863
Reputation: 1579
You are probably not going to get around casting in this case, meaning this is how the validate
method would look like:
@SuppressWarnings("unchecked")
@Override
public <T> boolean validate(T request) {
if (validatorMap.containsKey(request.getClass())) {
IValidator<T> val = (IValidator<T>) validatorMap.get(request.getClass());
return val.isValid(request);
}
return true;
}
Upvotes: 6