-2

I am trying to create objects (implement factory pattern) using Java 8 lambda and Supplier interface.

public static void main(final String[] args) {
    FactoryEnum.getEnumByClassName("CLASS_A").getSupplier().execute();
    FactoryEnum.getEnumByClassName("CLASS_B").getSupplier().execute();
  }

enum FactoryEnum {

  CLASS_A(() -> A::new),

  CLASS_B(() -> B::new);

  private final Supplier<IConverter> supplier;

  FactoryEnum(final Supplier<IConverter> supplier) {
    this.supplier = supplier;
  }

  public static FactoryEnum getEnumByClassName(final String className) {
    return FactoryEnum.valueOf(className);
  }

  public IConverter getSupplier() {
    return supplier.get();
  }
}

interface IConverter {

  void execute();
}

class A implements IConverter {

  @Override
  public void execute() {

    System.out.println("Inside A"); //$NON-NLS-1$
  }

}

class B implements IConverter {

  @Override
  public void execute() {
    System.out.println("Inside B");
  }

}

When I call FactoryEnum.getEnumByClassName("CLASS_A").getSupplier().execute() I was expecting this to return an newly created Object of Class A and FactoryEnum.getEnumByClassName("CLASS_A").getSupplier().execute() and this to return newly created object of Class B. While it is returning me an Lambda. Why is it returning lambda rather then an Object of IConverter. And how I can get that?

Gaurav Jeswani
  • 4,410
  • 6
  • 26
  • 47
  • Question got closed before I could submit my answer. While it *is* a typo, I think an explanation of *why* it's a typo might be useful. Here it is https://pastebin.com/Q6bxCZhg – Michael Nov 27 '20 at 13:33
  • 4
    There is, by the way, no sense in creating an additional method `getEnumByClassName` that does the same as the already existing `valueOf` method, especially when its only feature, the distinct name, is misleading, as the argument is *not* a class name. – Holger Nov 27 '20 at 13:35
  • @Michael : Thanks for your help. I wrote this intentionally, because Actually I got the interpretation of A::new to new A(), while it is () -> {new A()}. – Gaurav Jeswani Nov 27 '20 at 13:35
  • @Holger Yes, totally make sense. Thanks for mentioning it. – Gaurav Jeswani Nov 27 '20 at 13:36

1 Answers1

3
CLASS_A(() -> A::new)

means

CLASS_A(() -> { return A::new; })

which means

CLASS_A(() -> { return () -> { new A(); }; })

which isn't what you were trying to convey.

Try

CLASS_A(A::new)
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142