我刚开始学习Java,正在学习构造函数。我发现有些例子中将构造函数作为参数传递给方法。请告诉我当构造函数作为方法的参数时会发生什么,或者建议我一些链接,以获取关于使用构造函数的足够知识。
我刚开始学习Java,正在学习构造函数。我发现有些例子中将构造函数作为参数传递给方法。请告诉我当构造函数作为方法的参数时会发生什么,或者建议我一些链接,以获取关于使用构造函数的足够知识。
根据您需要传递构造函数的目的,您可以考虑传递Supplier实例而不是构造函数(JavaDoc-https://docs.oracle.com/javase/8/docs/api/java/util/function/Supplier.html)。 例如,您有一个方法,该方法应该创建一个账户并填写所有内容。您可以将此方法设置为接受Supplier作为参数:
public Account createNewAccount(Supplier<Account> accountConstructor) {
var account = accountConstructor.get();
account.fillEverything();
return account;
}
接下来,您可以使用lambda将构造函数传递给此方法:
createNewAccount(() -> new UserAccount());
或者使用方法引用:
createNewAccount(UserAccount::new);
constructItem
方法时调用其中一个。第一个构造函数被存储为返回类型为S
的Supplier
对象,而第二个构造函数则接受一个以类型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);
}
}
x
,通过带一个参数调用构造函数创建y
。ConstructorWrapper<Set, ArrayList> setToArrayList = new ConstructorWrapper<>(ArrayList::new, ArrayList::new);
ArrayList x = setToArrayList.constructItem(null);
ArrayList y = setToArrayList.constructItem(new HashSet<>());
或者像这样从ArrayList创建Sets:
ConstructorWrapper<ArrayList, HashSet> arrayListsToSets = new ConstructorWrapper<>(HashSet::new, HashSet::new);
HashSet x = arrayListsToSets.constructItem(null);
HashSet y = arrayListsToSets.constructItem(new ArrayList<>());
我使用了原始的ArrayList和Set,因为我不想在代码中增加更多的泛型而使其凌乱。
构造函数可以使用方法引用作为参数传递给方法,有点像C++中的函数指针。
参见:http://www.baeldung.com/java-8-double-colon-operator
这可以是一个带有一个参数的Function类型或带有两个参数的BiFunction类型,无论哪种方式,它都是返回其构造的类型的lambda。
不过,就像Turing85所说,我认为这不是你想要的。将构造函数作为参数传递是一个相当小众的用例。如果您只想了解构造函数的信息,
https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html