创建一个用于从已实例化的对象中创建新实例的供应商的Java代码。

huangapple go评论64阅读模式
英文:

Java: Creating a Supplier for a new instance of an Object from an instantiated Object

问题

我想从一个现有的Java对象创建一个Java `Supplier`。像这样的东西可以做到

```java
CustomObject customObject = new CustomObject();
Supplier<CustomObject> newInstanceSupplier = Supplier.of(customObject);

然而,对于Java来说,Supplier的这种语法是不存在的,我想知道是否有一个方便的解决方法。

我知道我可以轻松地创建一个供应商,像这样:

Supplier<CustomObject> supplier = () -> new CustomObject();

或者

Supplier<CustomObject> supplier = CustomObject::new;

然而,在我的用例中,我想从一个现有的自定义对象中获取Supplier,以实现抽象化。

是否有一种方便的方法来做到这一点?

这个问题解决了一个略有不同的方法。


<details>
<summary>英文:</summary>

I want to create a Java `Supplier` from an existing instantiated Java object. Something like this would do:

CustomObject customObject = new CustomObject();
Supplier<CustomObject> newInstanceSupplier = Supplier.of(customObject)

This syntax for `Supplier` however does not exist for Java and I am wondering whether there is a convenient solution to this one. 

I know I could easily create a supplier like this:

Supplier<CustomObject> supplier = ()-> new CustomObject()

or

Supplier<CustomObject> supplier = CustomObject::new


However, in my use-case, I want to take the `Supplier` from an existing custom object to allow for abstraction.

Is there a convenient way to do so?

This [question](https://stackoverflow.com/questions/45142151/how-to-get-a-supplier-from-an-instance) tackles a slightly different approach.

</details>


# 答案1
**得分**: 4

Suppliers are not created that way. There is no static method `Supplier#of(...)` in the standard JDK.

If you want to create a `Supplier` supplying a previously created instance, do this:

```java
CustomObject customObject = new CustomObject();
Supplier<CustomObject> supplier = () -> customObject;

Though doing this, you lose the benefits of lazy instantiation as the instance becomes always instantiated before and regardless of whether the supplier is called or not.

Finally, remember the instance customObject must be marked as final or stay "effectively final", i.e. you can't reassign to it anything else.

英文:

Suppliers are not created that way. There is no static method Supplier#of(...) in the standard JDK.

If you want to create a Supplier supplying a previously created instance, do this:

CustomObject customObject = new CustomObject();
Supplier&lt;CustomObject&gt; supplier = () -&gt; customObject;

Though doing this, you lose the benefits of lazy instantiation as the instance becomes always instantiated before and regardless of whether the supplier is called or not.

Finally, remember the instance customObject must be marked as final or stay "effectively final", i.e. you can't reassign to it anything else.

huangapple
  • 本文由 发表于 2023年7月13日 10:47:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76675571.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定