如何在Java中将函数作为参数传递? [英] How to pass a function as a parameter in Java?

查看:1200
本文介绍了如何在Java中将函数作为参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将方法作为参数传递给Java方法?如果是这样,有人可以指导我吗?这看起来并不简单

Is it possible to pass a method into a Java method as a parameter? If so, could someone please guide me? This doesn't seem trivial

推荐答案

Java 8及以上



使用Java 8+ lambda表达式,如果您的类或接口只有一个方法,例如:

Java 8 and above

Using Java 8+ lambda expressions, if you have a class or interface with only a single method, for example:

public interface MyInterface {
    String doSomething(int param1, String param2);
}

然后在任何使用MyInterface的地方,你可以替换lambda表达式:

then anywhere where MyInterface is used, you can substitute a lambda expression:

class MyClass {
    public MyInterface myInterface = (p1, p2) -> { return p2 + p1; };
}

例如,您可以非常快速地创建新线程:

For example, you can create a new thread very quickly:

new Thread(() -> someMethod()).start();

并使用方法参考语法,使其更清晰:

new Thread(this::someMethod).start();

如果没有 lambda表达式,最后两个示例将如下所示:

Without lambda expressions, these last two examples would look like:

new Thread(new Runnable() { someMethod(); }).start();



Java 8之前



常见模式就是在一个界面中包裹它,例如 Callable ,然后传入一个Callable:

Before Java 8

A common pattern would be to 'wrap' it within an interface, like Callable, for example, then you pass in a Callable:

public T myMethod(Callable<T> func) {
    return func.call();
}

此模式称为命令模式

请记住,最好为您创建一个界面特殊用途。如果您选择使用callable,那么您将使用您期望的任何类型的返回值替换上面的T,例如String。

Keep in mind you would be best off creating an interface for your particular usage. If you chose to go with callable, then you'd replace T above with whatever type of return value you expect, such as String.

回复您下面的评论可以说:

In response to your comment below you could say:

public int methodToPass() { 
        // do something
}

public void dansMethod(int i, Callable<Integer> myFunc) {
       // do something
}

然后调用它,可能使用匿名内部类:

then call it, perhaps using an anonymous inner class:

dansMethod(100, new Callable<Integer>() {
   public Integer call() {
        return methodToPass();
   }
});

请记住,这不是'技巧'。它只是java的基本概念等价于函数指针。

Keep in mind this is not a 'trick'. It's just java's basic conceptual equivalent to function pointers.

这篇关于如何在Java中将函数作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆