java—如何定义一个枚举,其中有零个或多个使用者在公共接口的实现上操作?

evrscar2  于 2021-07-06  发布在  Java
关注(0)|答案(0)|浏览(229)

我有以下类似的代码(尽可能简化),编译:

  1. class Test {
  2. enum TestEnum {
  3. ELEMENT1(Test::methodUsingTestclass1);
  4. <T extends TestInterface> TestEnum(Consumer<T>... consumers) {
  5. }
  6. }
  7. static void methodUsingTestclass1(TestClass1 testClass1) {
  8. }
  9. static void methodUsingTestclass2(TestClass2 testClass2) {
  10. }
  11. interface TestInterface {
  12. }
  13. class TestClass1 implements TestInterface {
  14. }
  15. class TestClass2 implements TestInterface {
  16. }
  17. }

现在我想指定 Consumer 她在我的房间里 enum :

  1. enum TestEnum {
  2. ELEMENT1(Test::methodUsingTestclass1, Test::methodUsingTestclass2);
  3. <T extends TestInterface> TestEnum(Consumer<T>... consumers) {
  4. }
  5. }

它不再编译:
类型参数t的上限不兼容:test.testclass1和test.testclass2 T 工具 TestInterface ,我想定义一个或多个 Consumer 他在做手术 T . 换句话说,方法引用的列表,这些方法引用接受 TestInterface .
我试过这个:

  1. enum TestEnum {
  2. ELEMENT1(Test::methodUsingTestclass1, Test::methodUsingTestclass2);
  3. <T extends TestInterface> TestEnum(Consumer<? extends T>... consumers) {
  4. }
  5. }

但我仍然得到同样的编译错误。
如何修改代码使其构造函数接受零或更多 Consumer 在不同的实现上运行 TestInterface ?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题