原创

JAVA8系列教程-Generic Functional 接口

温馨提示:
本文最后更新于 2019年12月14日,已超过 1,883 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

学习Java 8及更高版本中创建具有类型限制和不具有类型限制的Generic Functional接口请注意,Functional接口仅允许一种抽象方法。这些接口也称为单一抽象方法接口(SAM接口)

1.无类型限制的Generic Functional

1.1。接口定义

可以定义一个类型通用的功能接口,X并具有一个可以接受两个type参数X并返回type值的功能方法X

通用功能接口
package com.howtodoinjava.java8.example;
 
@FunctionalInterface
public interface ArgumentsProcessor<X>
{
    X process(X arg1, X arg2);
}

该接口可被用于任何类型的,即ArgumentsProcessor<Integer>ArgumentsProcessor<String>ArgumentsProcessor<Employee>

1.2。

使用类型为的通用功能接口的Java示例Integer

功能接口示例-1
package com.howtodoinjava.java8.example;
 
public class Main
{
    public static void main(String[] args)
    {
        ArgumentsProcessor<Integer> multiplyProcessor = new ArgumentsProcessor<Integer>() {
            @Override
            public Integer process(Integer arg1, Integer arg2)
            {
                return arg1 * arg2;
            }
        };
         
        System.out.println(multiplyProcessor.process(2,3));     //6
    }
}

使用类型为的通用功能接口的Java示例String

功能接口示例-1
package com.howtodoinjava.java8.example;
 
public class Main
{
    public static void main(String[] args)
    {
        ArgumentsProcessor<String> appendProcessor = new ArgumentsProcessor<String>() {
            @Override
            public String process(String str1, String str2)
            {
                return str1  + " " + str2;
            }
        };
         
        System.out.println(appendProcessor.process("Hello", "World !!"));   //Hello World !!
    }
}

2.具有类型限制的Generic Functional

2.1 接口定义

可以使用关键字ie 定义功能接口,将其限制为某些类型extendsX extends Number

具有类型限制的通用功能接口
package com.howtodoinjava.java8.example;
 
@FunctionalInterface
public interface ArgumentsProcessor<X extends Number>
{
    X process(X arg1, X arg2);
}

该接口可用于任何类型,即ArgumentsProcessor<Integer>ArgumentsProcessor<Double>但不能用于ArgumentsProcessor<String>ArgumentsProcessor<Employee>

在上面的示例中,允许的类型必须扩展Number该类。

2.2 样例

使用类型为的通用功能接口的Java示例Integer

功能接口示例
package com.howtodoinjava.java8.example;
 
public class Main
{
    public static void main(String[] args)
    {
        ArgumentsProcessor<Double> doubleMultiplier = new ArgumentsProcessor<Double>() {
            @Override
            public Double process(Double arg1, Double arg2)
            {
                return arg1 * arg2;
            }
        };
         
        System.out.println(doubleMultiplier.process(4d, 6d));   //24.0
    }
}

3.专用Functional接口

通过扩展或实现一种类型的通用功能接口来实现专业化。结果接口或类对于该类型不是通用的。

具有专用功能的通用功能接口
package com.howtodoinjava.java8.example;
 
@FunctionalInterface
public interface ArgumentsProcessor<Integer>
{
    Integer process(Integer arg1, Integer arg2);
}
使用lambda的功能接口示例
package com.howtodoinjava.java8.example;
 
public class Main {
    public static void main(String[] args)
    {
        ArgumentsProcessor<Integer> intMultiplier = (i1, i2) -> i1 * i2;
 
        System.out.println(intMultiplier.process(4, 5));    //20
    }
}
正文到此结束
本文目录