基于通用接口的实现限制java中的泛型类型

时间:2022-01-09 19:22:28

So I have got 2 generic interfaces.

所以我有2个通用接口。

First interface is implemented like this.

第一个接口是这样实现的。

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 the second interface's (second interface is shown below) generic type to allow only the classes that are used when implementing the first interface, in our case String and Double. Is there any clean way to do this, something like

我需要第二个接口(第二个接口如下所示)泛型类型,只允许在实现第一个接口时使用的类,在我们的例子中是String和Double。是否有任何干净的方法来做这件事,比如

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); }
}

, so the in Second's generic E would fit only String and Double and all classes that are used to implement First<E>?

,那么在Second的通用E中只适合String和Double以及用于实现First 的所有类?

1 个解决方案

#1


Nope. You can not restrict the generic type of the Second in that sense. You can still provide an another type information independently. Say,

不。在这个意义上,您不能限制Second的泛型类型。您仍然可以单独提供其他类型的信息。说,

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

an another class may provide an another type information for the Second, like

另一个类可以为第二类提供另一种类型的信息,如

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

assuming SomeOtherType implements/extends whatever from type First. If you want to bind those two interfaces on their generic type, you can use inheritance between the implementations:

假设SomeOtherType实现/扩展类型First中的任何内容。如果要在它们的泛型类型上绑定这两个接口,可以在实现之间使用继承:

  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, the type E, is associated with the type T, via E extends T.

现在,类型E与类型T相关联,通过E扩展T.

#1


Nope. You can not restrict the generic type of the Second in that sense. You can still provide an another type information independently. Say,

不。在这个意义上,您不能限制Second的泛型类型。您仍然可以单独提供其他类型的信息。说,

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

an another class may provide an another type information for the Second, like

另一个类可以为第二类提供另一种类型的信息,如

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

assuming SomeOtherType implements/extends whatever from type First. If you want to bind those two interfaces on their generic type, you can use inheritance between the implementations:

假设SomeOtherType实现/扩展类型First中的任何内容。如果要在它们的泛型类型上绑定这两个接口,可以在实现之间使用继承:

  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, the type E, is associated with the type T, via E extends T.

现在,类型E与类型T相关联,通过E扩展T.