How to define an enum with zero or more Consumers operating on implementations of a common interface?

Viewed 88

I have something like the below code (simplified as much as possible), which compiles:

class Test {

  enum TestEnum {
    ELEMENT1(Test::methodUsingTestclass1);

    <T extends TestInterface> TestEnum(Consumer<T>... consumers) {
    }
  }

  static void methodUsingTestclass1(TestClass1 testClass1) {
  }

  static void methodUsingTestclass2(TestClass2 testClass2) {
  }

  interface TestInterface {
  }

  class TestClass1 implements TestInterface {
  }

  class TestClass2 implements TestInterface {
  }

}

Now I want to be able to specify a vararg of Consumers in my enum:

enum TestEnum {
  ELEMENT1(Test::methodUsingTestclass1, Test::methodUsingTestclass2);

  <T extends TestInterface> TestEnum(Consumer<T>... consumers) {
  }
}

This no longer compiles:

Type parameter T has incompatible upper bounds: Test.TestClass1 and Test.TestClass2

T implements TestInterface, and I would like to define one or more Consumers operating on T. In other words, a list of method references to methods accepting an implementation class of TestInterface.

I have tried this:

enum TestEnum {
  ELEMENT1(Test::methodUsingTestclass1, Test::methodUsingTestclass2);

  <T extends TestInterface> TestEnum(Consumer<? extends T>... consumers) {
  }
}

But I still get the same compile error.

How can the code be modified so that its constructor accepts zero or more Consumers operating on different implementations of TestInterface?

0 Answers
Related