简体   繁体   English

Java中的JavaScript匿名函数

[英]JavaScript Anonymous functions in Java

I am new to JavaScript and have some intermediate knowledge of Java, after a few exercise, I am left with a puzzling question is there a way to apply the concept of anonymous functions in Java? 我是JavaScript的新手,并且具有Java的一些中级知识,经过几次练习后,我感到一个令人困惑的问题,是否有办法在Java中应用匿名函数的概念? is it even possible? 可能吗? I am well aware of the criticism I might receive for asking this question but I am asking anyway. 我很清楚我可能会因提出这个问题而受到批评,但无论如何我都是在问。 An example of JavaScript anonymous function is below. 下面是一个JavaScript匿名函数的示例。

var myResult = (function () {
            return arguments[0] + arguments[1];
    }) (1,2);
alert(myResult);

Using @FunctionalInterface Java 8 使用@FunctionalInterface Java 8

public class Test {
    @FunctionalInterface
        public interface Func {
        public String concat(String a, String b);
    }

    public static void main(String[] args) {
        Func func = (a, b) -> a + b;
        System.out.print(func.concat("Hello ", "World!"));
    }
}

Anonymous inner classes do exactly that. 匿名内部类正是这样做的。 A function cannot exist on its own in Java; 在Java中,函数不能独立存在; it has to be wrapped in a class. 它必须包装在一个类中。 So, the closest thing to an anonymous function is an anonymous inner class. 因此,最接近匿名函数的是匿名内部类。

int myResult = (new Object() {
public int calc(int[] args){
        return args[0] + args[1];
    } }).calc( new int[]{ 1, 2} );
System.out.println(myResult);

This can now be easily done using Java 8 using lambda expressions (with functional interfaces). 现在,可以使用Java 8使用lambda表达式(具有功能接口)轻松地完成此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM