我正在寻找一种通过引用传递方法的方法.我知道Java不会将方法作为参数传递,但是,我想获得一个替代方案.
我被告知接口是将方法作为参数传递的替代方法,但我不明白接口如何通过引用充当方法.如果我理解正确,接口只是一组未定义的抽象方法.我不希望每次都发送需要定义的接口,因为几种不同的方法可以使用相同的参数调用相同的方法.
我想要完成的是类似的事情:
public void setAllComponents(Component[] myComponentArray, Method myMethod) {
for (Component leaf : myComponentArray) {
if (leaf instanceof Container) { //recursive call if Container
Container node = (Container) leaf;
setAllComponents(node.getComponents(), myMethod);
} //end if node
myMethod(leaf);
} //end looping through components
}
Run Code Online (Sandbox Code Playgroud)
调用如:
setAllComponents(this.getComponents(), changeColor());
setAllComponents(this.getComponents(), changeSize());
Run Code Online (Sandbox Code Playgroud) 可能重复:
Java Pass方法作为参数
是否可以在Java中将方法作为参数传递?如果我不能重复代码,那么下面的方法将是最好的行动方案.
public void enterUserInput(javax.swing.JTextField inputField, javax.swing.JTextField outputField, method rangeChecking){
String input;
double output;
input = inputField.getText();
output = Double.parseDouble(input);
if(rangeChecking(output)){
outputField.setText(input);
inputField.setText(null);
}
Run Code Online (Sandbox Code Playgroud)
我将从不同的类调用rangeChecking方法,每次调用enterUserInput时,rangeChecking方法都会有所不同
我遇到了Java 8方法引用与泛型类型相结合的问题.我已经简化了我的问题,以明确问题所在.以下代码失败:
public static void main(String[] args) {
new Mapper(TestEvent::setId);
}
private static class Mapper<T> {
private BiConsumer<TestEvent, T> setter;
private Mapper(BiConsumer<TestEvent, T> setter) { this.setter = setter; }
}
private static class TestEvent {
public void setId(Long id) { }
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我将构造函数调用更改为
BiConsumer<TestEvent, Long> consumer = TestEvent::setId;
new Mapper(consumer);
Run Code Online (Sandbox Code Playgroud)
一切正常.有人可以解释原因吗?
我知道如果我删除泛型类型(T)并使用Long代替它可行,但在解决我的实际问题时这不起作用.
我不明白如何使用lambdas将方法作为参数传递.
考虑以下(不编译)代码,如何完成它以使其工作?
public class DumbTest {
public class Stuff {
public String getA() {
return "a";
}
public String getB() {
return "b";
}
}
public String methodToPassA(Stuff stuff) {
return stuff.getA();
}
public String methodToPassB(Stuff stuff) {
return stuff.getB();
}
//MethodParameter is purely used to be comprehensive, nothing else...
public void operateListWith(List<Stuff> listStuff, MethodParameter method) {
for (Stuff stuff : listStuff) {
System.out.println(method(stuff));
}
}
public DumbTest() {
List<Stuff> listStuff = new ArrayList<>();
listStuff.add(new Stuff());
listStuff.add(new Stuff());
operateListWith(listStuff, methodToPassA); …Run Code Online (Sandbox Code Playgroud)