I'm dealing with some legacy code, trying to refactor and extract common code. I've ended up with the following hierarchy.
public interface MyInterface<T extends MyBaseClass> {...}
public class MyBaseClass {...}
public class MyClass extends MyBaseClass implements MyOtherInterface<MyClass> {...}
public interface MyOtherInterface<T extends MyOtherInterface<T>> {
void func(MyInterface<T> context); // Complains that T should extend MyBaseClass
}
In words, I want to specify that the parameter T passed to MyOtherInterface should be a class that extends MyBaseClass and implements MyOtherInterface. Something like this:
public interface MyOtherInterface<T extends MyOtherInterface<T extends MyBaseClass>>
How can I do this? I am trying to change as little as possible. I am not sure the above is possible and I might have to actually flip the hierarchy.
From Oracle's Java tutorial:
Multiple Bounds
The preceding example illustrates the use of a type parameter with a single bound, but a type parameter can have multiple bounds:
<T extends B1 & B2 & B3> A type variable with multiple bounds is a subtype of all the types listed in the bound. If one of the bounds is a class, it must be specified first. For example:
Class A { /* ... */ } interface B { /* ... */ } interface C { /* ...
*/ }
class D <T extends A & B & C> { /* ... */ } If bound A is not specified first, you get a compile-time error:
class D <T extends B & A & C> { /* ... */ } // compile-time error
Source: https://docs.oracle.com/javase/tutorial/java/generics/bounded.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With