简体   繁体   English

如何将复制构造函数作为方法引用传递?

[英]How do I pass a copy constructor as a method reference?

I have a class PlanItemEditor. 我有一个PlanItemEditor类。

I require the E item's copy constructor. 我需要E项的复制构造函数。 How do I pass it in 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 of including a Unary function as a parameter, and passing in a method from the E class that was exactly a copy constructor, but with a different name signature. 我正在考虑将一个Unary函数作为参数包含在内,并从E类中传入一个完全是复制构造函数但具有不同名称签名的方法。 It's kind of hacky, however. 然而,这有点像hacky。

Is there a better way of doing this? 有没有更好的方法呢?

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 复制 object 的引用或将其传递给方法/构造函数是线程安全的吗? - Copy the reference of an object or pass it in a method/constructor is thread safe? 构造函数还是main()? 我如何将渗透系数传递给该方法? - Constructor or main()? How do I pass in perameters to the method? 如何将变量从方法传递给构造函数 - How do I pass a variable from a method to a constructor 如何将构造函数传递给构造函数? - How do I pass a constructor to a constructor? 传递参数化构造函数作为方法引用 - pass parameterized constructor as method reference 如何将对外部类的引用传递给内部类中的方法? (或者如何将“ this”传递给内部类?) - How do I pass a reference to the outer class to a method in an inner class? ( Or how do I pass “this” to an inner class? ) 如何将值传递给构造函数并从同一类的方法中使用它? - How do I pass a value to a constructor and use it from a method in the same class? 如何验证构造函数中的方法调用? - How do I verify a method call that is in a constructor? 当它在流中作为方法引用出现时,如何模拟构造函数? - How can I mock a constructor when it appears as a method reference in a stream? 如何在Java RMI中使用可序列化对象和回调方法正确模仿传递引用? - How do I properly mimic pass-by-reference in Java RMI with serializable objects and a callback method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM