简体   繁体   中英

Generics with wildcard not compiling

The following code is not compiling:

public class Example {

    public void method() {
        Callback<BaseResponse> br = null;
        Request<? extends BaseResponse> req = null;
        req.startRequest(br); //compile-time error here!!
    }

    public interface Callback<T> {
        void onResponse (T response);
        void onFailure (String error, int code);
        void onFailure (Throwable t);
    }

    public static class BaseResponse {
        public String status;
    }

    public interface Request<BaseResponse> {
        void startRequest(Callback<BaseResponse> callback);
    }
}

If I take away the ? extends ? extends part then the code compiles, but I need it in. I can't understand why is it not compiling? Looks perfectly "type safe" to me.

What workarounds or design changes should I make to get this to work?

Your problem is on the line

public interface Request<BaseResponse> {

where you've made BaseResponse a type parameter, and effectively hidden the class of the same name. You probably meant to write

public interface Request<T extends BaseResponse> {

or something similar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM