Ben*_*key 147 java delegates pointers function-pointers
这可能是常见和微不足道的事情,但我似乎无法找到具体的答案.在C#中有一个委托的概念,它与C++中的函数指针的思想密切相关.Java中是否有类似的功能?鉴于指针有点缺席,最好的方法是什么?要说清楚,我们在这里谈论头等舱.
Mic*_*rdt 125
类似于函数指针的功能的Java习惯用法是一个实现接口的匿名类,例如
Collections.sort(list, new Comparator<MyClass>(){
public int compare(MyClass a, MyClass b)
{
// compare objects
}
});
Run Code Online (Sandbox Code Playgroud)
更新:在Java 8之前的Java版本中,上述内容是必需的.现在我们有更好的替代方案,即lambdas:
list.sort((a, b) -> a.isGreaterThan(b));
Run Code Online (Sandbox Code Playgroud)
和方法参考:
list.sort(MyClass::isGreaterThan);
Run Code Online (Sandbox Code Playgroud)
rau*_*ach 64
您可以使用接口替换函数指针.假设你想要运行一个集合并对每个元素做一些事情.
public interface IFunction {
public void execute(Object o);
}
Run Code Online (Sandbox Code Playgroud)
这是我们可以传递给CollectionUtils2.doFunc(Collection c,IFunction f)的接口.
public static void doFunc(Collection c, IFunction f) {
for (Object o : c) {
f.execute(o);
}
}
Run Code Online (Sandbox Code Playgroud)
举个例子说我们有一个数字集合,你想为每个元素添加1.
CollectionUtils2.doFunc(List numbers, new IFunction() {
public void execute(Object o) {
Integer anInt = (Integer) o;
anInt++;
}
});
Run Code Online (Sandbox Code Playgroud)
小智 41
你可以使用反射来做到这一点.
将参数作为参数传递给对象和方法名称(作为字符串),然后调用该方法.例如:
Object methodCaller(Object theObject, String methodName) {
return theObject.getClass().getMethod(methodName).invoke(theObject);
// Catch the exceptions
}
Run Code Online (Sandbox Code Playgroud)
然后使用它,如:
String theDescription = methodCaller(object1, "toString");
Class theClass = methodCaller(object2, "getClass");
Run Code Online (Sandbox Code Playgroud)
当然,检查所有异常并添加所需的强制转换.
要实现类似的功能,您可以使用匿名内部类.
如果要定义接口Foo:
interface Foo {
Object myFunc(Object arg);
}
Run Code Online (Sandbox Code Playgroud)
创建一个bar接收"函数指针"作为参数的方法:
public void bar(Foo foo) {
// .....
Object object = foo.myFunc(argValue);
// .....
}
Run Code Online (Sandbox Code Playgroud)
最后调用方法如下:
bar(new Foo() {
public Object myFunc(Object arg) {
// Function code.
}
}
Run Code Online (Sandbox Code Playgroud)
Java8引入了lambda和方法引用.因此,如果您的函数与功能界面匹配(您可以创建自己的界面),则可以在这种情况下使用方法引用.
Java提供了一组通用的功能接口.而你可以做以下事情:
public class Test {
public void test1(Integer i) {}
public void test2(Integer i) {}
public void consumer(Consumer<Integer> a) {
a.accept(10);
}
public void provideConsumer() {
consumer(this::test1); // method reference
consumer(x -> test2(x)); // lambda
}
}
Run Code Online (Sandbox Code Playgroud)
Java中没有这样的东西.您需要将函数包装到某个对象中,并将引用传递给该对象,以便将引用传递给该对象上的方法.
从语法上讲,通过使用定义为类的成员变量的就地定义的匿名类或匿名类,可以在一定程度上缓解这种情况.
例:
class MyComponent extends JPanel {
private JButton button;
public MyComponent() {
button = new JButton("click me");
button.addActionListener(buttonAction);
add(button);
}
private ActionListener buttonAction = new ActionListener() {
public void actionPerformed(ActionEvent e) {
// handle the event...
// note how the handler instance can access
// members of the surrounding class
button.setText("you clicked me");
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
150798 次 |
| 最近记录: |