When working with generics in Java, you may encounter the need to restrict the type of a generic class to extend a specific class and implement a particular interface. While it seems reasonable to expect that the following attempts would be successful:
Class<? extends ClassA>
Class<? extends InterfaceB>
Unfortunately, only one of these can be applied at a time. So, how can we combine the two restrictions?
In fact, it is possible to specify multiple interfaces or a class and interfaces in a generic type parameter using "&":
<T extends ClassA & InterfaceB>
This allows us to define a generic type that is restricted to both extending the specified class and implementing the specified interface.
For example, if we define a class ClassB and an interface InterfaceC, we can create a generic class as follows:
class MyClass<T extends ClassB & InterfaceC> { Class<T> variable; }
This ensures that the variable field of MyClass can only hold references to classes that extend ClassB and implement InterfaceC.
While this feature provides flexibility for defining generic types, it can also lead to complex declarations, as seen in the JavaDoc declaration of Collections#max:
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)
This complexity arises due to considerations for binary compatibility. However, it is important to note that this complexity is primarily encountered when defining generic classes or methods, and not when declaring generic variables.
Therefore, to achieve your goal of creating a class object that extends a specific class and implements a specific interface, you can use the following approach:
class classB { } interface interfaceC { } public class MyClass<T extends classB & interfaceC> { T variable; }
This will give you the desired restriction for the variable field of MyClass.
The above is the detailed content of How Can I Restrict a Java Generic Class to Extend a Class and Implement an Interface Simultaneously?. For more information, please follow other related articles on the PHP Chinese website!