java8自定义函数接口

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29493353/article/details/84103028

java8开始可以自定义函数式接口,方便开发人员使用lambda表达式,简化了代码量。

1.首先定义一个函数式接口(使用泛型能过更好的适配所有对象的操作)

    

/**
 * Represents a function that accepts two argument and produces a result.
 *
 *
 * whose functional method is {@link #Do(Object)}.
 *
 * @param <A> the first of the input to the function
 * @param <B> the second of the result of the function
 * @param <C>  the return value
 * @since 1.8
 */
@FunctionalInterface
public interface MyFunction<A,B,C> {

    C Do(A a,B b);
}

2.直接运行main方法

public class MyFunctionTest {

    public static void main(String[] args){

        MyFunction fun = (a,b) -> (int) a+ (int)b;
        System.out.println(fun.Do(1,2));
    }
}

以上是最简单的写法,显式的调用了Do方法。

剩余的代码封装,其余的接口和抽象类的定义就看个人功底了。想要熟悉函数接口使用,可以去看看集合类的stream使用。

也可以参考http://www.runoob.com/java/java8-functional-interfaces.html

https://github.com/winterbe/java8-tutorial

猜你喜欢

转载自blog.csdn.net/qq_29493353/article/details/84103028