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);
}
The Java compiler internally represents the value of a wildcard by capturing it in an anonymous type variable, which it calls "capture of ?" (actually, javac calls them "capture #1 of ?" because different uses of ? may refer to different types, and therefore have different captures).
In some cases, the compiler infers the type of a wildcard. For example, a list may be defined as List<?> but, when evaluating an expression, the compiler infers a particular type from the code. This scenario is known as wildcard capture.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With