简体   繁体   中英

In java Generics, how to extend an interface instead of a class

I would like to make something similar to Class<? extends MyParentClass>> Class<? extends MyParentClass>> but using an interface, something like

Class<? implements MyInterfaceClass>

but i got this error:

- Incorrect number of arguments for type Class<T>; it cannot be parameterized with arguments <?, 
     MyInterfaceClass>

but It seems that is not possible ?

Yes, it is possible. But in world of generics there is no implements but only extends and super so simply use extends (even if you are working with interface).

Class<? extends MyInterfaceClass>
//      ^^^^^^^

Example:

Class<? extends Runnable> taskClass;

You still use the word extends instead of implements

For example

public interface MyInterface {
}

public class Demo {
    private Class<? extends MyInterface> myClass;
}

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