Java Lambda Expression Constructor Reference for class factory

Introduction

The following program uses a static method named myClassFactory() to create objects of any type of MyFunc objects.

// Implement a simple class factory using a constructor reference. 

interface MyFunc<R, T> {
  R func(T n);//w  w w  .  j  a  v  a2 s .c om
}

// A simple generic class.
class MyClass<T> {
  private T val;

  // A constructor that takes an argument.
  MyClass(T v) {
    val = v;
  }

  T getVal() {
    return val;
  };
}

class MyClass2 {
  String str;

  MyClass2(String s) {
    str = s;
  }

  String getVal() {
    return str;
  };
}

public class Main {
  static <R, T> R myClassFactory(MyFunc<R, T> cons, T v) {
    return cons.func(v);
  }

  public static void main(String args[]) {
    MyFunc<MyClass<Double>, Double> myClassCons = MyClass<Double>::new;

    // Create an instance of MyClass by use of the factory method.
    MyClass<Double> mc = myClassFactory(myClassCons, 100.1);

    System.out.println("val is " + mc.getVal());

    // create a different class 
    MyFunc<MyClass2, String> myClassCons2 = MyClass2::new;

    // Create an instance of MyClass2
    MyClass2 mc2 = myClassFactory(myClassCons2, "Lambda");

    System.out.println("str is " + mc2.getVal());
  }
}



PreviousNext

Related