我正在探索Java 8源代码,发现代码的这一特定部分非常令人惊讶:
//defined in IntPipeline.java
@Override
public final OptionalInt reduce(IntBinaryOperator op) {
return evaluate(ReduceOps.makeInt(op));
}
@Override
public final OptionalInt max() {
return reduce(Math::max); //this is the gotcha line
}
//defined in Math.java
public static int max(int a, int b) {
return (a >= b) ? a : b;
}
Run Code Online (Sandbox Code Playgroud)
是Math::max什么样的方法指针?普通static方法如何转换为IntBinaryOperator?
我正在寻找一种通过引用传递方法的方法.我知道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) 这可能是常见和微不足道的事情,但我似乎无法找到具体的答案.在C#中有一个委托的概念,它与C++中的函数指针的思想密切相关.Java中是否有类似的功能?鉴于指针有点缺席,最好的方法是什么?要说清楚,我们在这里谈论头等舱.
两种设计模式都封装了算法,并将实现细节与其调用类分离.我能辨别的唯一区别是策略模式接受执行参数,而命令模式则没有.
在我看来,命令模式要求所有执行信息在创建时都可用,并且它能够延迟其调用(可能作为脚本的一部分).
什么决定指导是使用一种模式还是另一种模式?
encapsulation design-patterns strategy-pattern command-pattern
我已经阅读了这个问题,我仍然不知道是否有可能继续指向方法Java中的数组,如果任何人知道,如果这是可能的,或者不是这将是一个真正的帮助.我正试图找到一个优雅的解决方案,保持一个字符串列表和相关的功能,而不会写出数百个'if'的混乱.
干杯
对于我的Java游戏服务器,我发送数据包的Action ID,它基本上告诉服务器数据包的用途.我想将每个Action ID(一个整数)映射到一个函数.有没有办法不使用开关这样做?
我想在java中实现类似javascript的方法,这可能吗?
说,我有一个Person类:
public class Person {
private String name ;
private int age ;
// constructor ,accessors are omitted
}
Run Code Online (Sandbox Code Playgroud)
以及包含Person对象的列表:
Person p1 = new Person("Jenny",20);
Person p2 = new Person("Kate",22);
List<Person> pList = Arrays.asList(new Person[] {p1,p2});
Run Code Online (Sandbox Code Playgroud)
我想实现这样的方法:
modList(pList,new Operation (Person p) {
incrementAge(Person p) { p.setAge(p.getAge() + 1)};
});
Run Code Online (Sandbox Code Playgroud)
modList接收两个参数,一个是列表,另一个是"函数对象",它循环列表,并将此函数应用于列表中的每个元素.在函数式编程语言中,这很容易,我不知道java是怎么做到的?也许可以通过动态代理完成,与原生for循环相比,它是否有性能折衷?
function objects在Java 中创建(无状态对象,导出一个适用于其他对象的方法)的最佳实践是什么?