Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
功能接口在Java8中的使用_Java_Lambda_Closures_Java 8 - Fatal编程技术网

功能接口在Java8中的使用

功能接口在Java8中的使用,java,lambda,closures,java-8,Java,Lambda,Closures,Java 8,这是一个后续问题,Java允许您使用::操作符引用方法 是否可以提供一些我创建的自定义功能接口,并与::操作员一起使用?怎么做呢 如何提供自定义功能接口实现以使用:操作员 public class TestingLambda { public static void main(String[] args) { int value1 = method(TestingLambda::customMethod1); int value2 = method(Te

这是一个后续问题,Java允许您使用
::
操作符引用方法


是否可以提供一些我创建的自定义功能接口,并与
::
操作员一起使用?怎么做呢

如何提供自定义功能接口实现以使用
操作员

public class TestingLambda {

    public static void main(String[] args) {
        int value1 = method(TestingLambda::customMethod1);
        int value2 = method(TestingLambda::customMethod2);

        System.out.println("Value from customMethod1: " + value1);
        System.out.println("Value from customMethod2: " + value2);
    } 

    public static int customMethod1(int arg){
        return arg + 1;
    }

    public static int customMethod2(int arg){
        return arg + 2;
    }

    public static int method(MyCustomInterface ob){
        return ob.apply(1);
    }

    @FunctionalInterface
    interface MyCustomInterface{
        int apply(int arg);
    }
}
阶段1:创建自定义功能接口 我已经创建了自己的
functionalterface
名为
MyCustomInterface
,在Java 8中,您必须使用
@functionalterface
注释将接口声明为functional interface。现在,它有一个方法,将
int
作为参数并返回
int

阶段2:创建一些方法来确认该签名 创建了两个方法
customMethod1
customMethod2
,以确认该自定义接口的签名

阶段3:创建一个以函数接口(
MyCustomInterface
)为参数的方法
方法
在参数中采用
MyCustomInterface

你准备好出发了

第4阶段:使用 大体上,我使用了
方法
,并将自定义方法的实现传递给它

method(TestingLambda::customMethod1); 

“是否可以提供一些我创建并与
操作员一起使用的自定义功能接口?以及如何实现?”

这是可能的,也很容易,就像你想象的那样:只需用一个方法创建一个接口。您甚至不需要
@functioninterface
注释;此注释仅记录您的意图,并帮助在编译时检测错误,类似于
@Override

所以,也许您已经在Java8之前的项目中创建了这样的接口

class Foo {
    // nothing new:
    public interface FooFactory {
        Foo createFoo();
    }
    // new in Java 8:
    public static final FooFactory DEFAULT_FACTORY = Foo::new;
}
给你

import java.util.Arrays;

class Sort {
    public int compareByLength(String s1, String s2) {
        return (s1.length() - s2.length());
    }
}

public class LambdaReferenceExample1 {
    public static void main(String[] javalatteLambda) {
        String[] str = {"one", "two", "3", "four", "five", "sixsix", 
            "sevennnnn", "eight"};
        Sort sort = new Sort();
        Arrays.sort(str, sort::compareByLength);

        for (String s : str) {
            System.out.println(s);
        }
    }
}

+感谢您指出我不需要@functionInterface。那么,你能为这个问题建议一个更好的标题吗?那么,
@functioninterface
→ 功能接口?术语“功能接口”是正确的。谢谢。编辑标题。