Required type capture of ?, provided T

edmundpie :

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

Schred :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=344674&siteId=1