英文:
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<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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论