How do I pass a copy constructor as a method reference?

I have a PlanItemEditor class.

I need a copy constructor for element E. How can I pass it using a method reference?

public void initValues(ObservableList<E> srcList, E toEdit) {
    indexToSet = srcList.indexOf(toEdit);
    editing = new E(toEdit);
    this.srcList = srcList;
}

      

I was thinking about including the Unary function as a parameter and passing a method from class E, which was exactly the copy constructor, but with a different name signature. However, this is hacking.

Is there a better way to do this?

+3


source to share


1 answer


You can use:

public void initValues(ObservableList<E> srcList, E toEdit, UnaryOperator<E> copy) {
    indexToSet = srcList.indexOf(toEdit);
    editing = copy.apply(toEdit);
    this.srcList = srcList;
}

      



And you can call it with:

initValues(srcList, toEdit, YourClass::new);

      

+3


source







All Articles