[英]Passing constructor as a parameter to a method
我是 java 的新手,並開始研究構造函數。 我看到了幾個將構造函數作為參數傳遞給方法的示例。 請告訴我當構造函數作為參數傳遞給方法時會發生什么......或者建議我一些鏈接,在那里我可以獲得關於使用構造函數的足夠知識
根據目的,為什么需要傳遞構造函數,可以考慮傳遞Supplier的實例(JavaDoc- https ://docs.oracle.com/javase/8/docs/api/java/util/function/Supplier 。 html )。 例如,您有一種方法可以創建一個帳戶並填寫其中的所有內容。 您可以使此方法接受供應商作為參數:
public Account createNewAccount(Supplier<Account> accountConstructor) {
var account = accountConstructor.get();
account.fillEverything();
return account;
}
然后使用lambda將構造函數傳遞給此方法:
createNewAccount(() -> new UserAccount());
或使用方法參考:
createNewAccount(UserAccount::new);
兩種變體都可以使用。
構造函數可以使用方法引用作為方法的補充,有點像C ++中的函數指針。
請參閱: http : //www.baeldung.com/java-8-double-colon-operator
這可以是帶有一個參數的Function類型,也可以是帶有兩個參數的BiFunction類型,可以是lambda返回其構造的類型的類。
就像Turing85所說的,盡管我認為這不是您想要的。 將構造函數作為參數傳遞是一個非常合適的用例。 如果您只想要有關構造函數的信息,
https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
下面是一個示例 class,它包含兩個構造函數作為實例變量,並在調用constructItem
方法時調用其中一個。 第一個構造函數存儲為Supplier
,返回類型S
的Function
,第二個構造函數采用類型T
並返回類型S
的 Function。
public class ConstructorWrapper<T, S> {
private final Supplier<S> construct;
private final Function<T, S> constructFromObject;
public ConstructorWrapper(Supplier<S> constructWithNothing, Function<T, S> constructWithObject) {
this.construct = constructWithNothing;
this.constructFromObject = constructWithObject;
}
public S constructItem(T k) {
if (k != null) return this.construct.get();
else return constructFromObject.apply(k);
}
}
我們可以像這樣使用 class 來包裝從 Sets 中創建 ArrayLists。 x
是通過調用不帶參數的構造函數創建的, y
是通過調用帶一個參數的構造函數創建的。
ConstructorWrapper<Set, ArrayList> setToArrayList = new ConstructorWrapper<>(ArrayList::new, ArrayList::new);
ArrayList x = setToArrayList.constructItem(null);
ArrayList y = setToArrayList.constructItem(new HashSet<>());
或者像這樣包裝從 ArrayLists 中創建的集合:
ConstructorWrapper<ArrayList, HashSet> arrayListsToSets = new ConstructorWrapper<>(HashSet::new, HashSet::new);
HashSet x = arrayListsToSets.constructItem(null);
HashSet y = arrayListsToSets.constructItem(new ArrayList<>());
我使用原始 ArrayLists 和 Sets 因為我不想用更多 generics 使代碼混亂
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.