简体   繁体   中英

Java generics return type

    public class Signal<T>{
        public void addListener(T listener){
            // do some thing
        }
    }

    public static <T> Signal<? extends T> inject(Class<? extends T> type) {
        // do some thing and return 
    }

    public void execute(MyInterface callback){
        Signal<? extends MyInterface> signal = inject(callback.getClass());
        signal.addListener(callback); // Compiler error
    }

I got a compiler error in the last raw, any idea how to fix it? I don't mind changing the implementation of inject or Signal class, my goal is to make execute method to work as it is now.

Try:

    public static <T> Signal<T> inject(Class<? extends T> type) {
        return null;
    }

    public void execute(MyInterface callback){
        Signal<MyInterface> signal = inject(callback.getClass());
        signal.addListener(callback);
    }

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