Limit generic types in java based on universal interface implementation

So, I have two common interfaces.

The first interface is implemented as follows.

public interface First<E> { void method(E e) } public class FirstImpl implements First<String> { void method(String s) { System.out.println(s); } } public class FirstImpl2 implements First<Double> { void method(Double d) { System.out.println(d); } } 

I need a second interface (the second interface is shown below) is a generic type that allows you to use only the classes that are used to implement the first interface, in our case String and Double . Is there any clean way to do this, something like

 public interface Second <E, ? extends First<E>> { void method(E e); } public class SecondImpl <E> implements Second <E, ? extends First<E>> { void method(E e) { System.out.println(e); } } 

therefore, in the second generic E will only String and Double and all classes that are used to implement First<E> correspond?

+6
source share
1 answer

Nope. You cannot limit the general type of the second in this sense. You can still provide other types of information independently. Let's say

 class XYZ implements First<Bar> { ... } 

another class can provide information of a different type for the second, for example

 class ZYX implements Second<Foo, SomeOtherType<Foo>> { ... } 

Assuming SomeOtherType implements / extends everything from the type First. If you want to associate these two interfaces with their common type, you can use inheritance between implementations:

  interface First<T> {} interface Second<T> {} class Foo<E extends T> implements First<T> {} class Bar<E extends T> extends Foo<E> implements Second<E> {} 

Now type E is associated with type T, through E continues T.

+1
source

Source: https://habr.com/ru/post/986927/


All Articles