Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Required type capture of ?, provided T

Tags:

java

generics

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);
}

like image 921
edmundpie Avatar asked Mar 22 '20 10:03

edmundpie


People also ask

What is capture of in Java?

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).

What is wildcard capture?

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.


1 Answers

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;
}
like image 128
cegredev Avatar answered Oct 19 '22 10:10

cegredev