当前位置:   article > 正文

JDK 8新特性 ——接口与函数式接口_static method may be invoked on containing interfa

static method may be invoked on containing interface class only

一、接口

1.1 接口组成更新概述

  • 常量

public static final 可以省略

  • 抽象方法

public abstract 可以省略

  • 默认方法(since java8)

如下图所示

  • 静态方法(since java8)

如下图所示

  • 私有方法(since java9)

1.2 默认方法

1.2.1 使用场景

假设我们已经存在一个劲接口MyInterface,但是随着业务的进行我们还需要在MyInterface接口中增加一个方法,但是如果我们增加的话,他的每个实现类都需要将这个方法进行实现。

此时有一个坏处,并不是每个类都能使用到这个接口,那我们就重新创建一个接口MyInterfaceSon去继承MyInterface接口,并且写上想增加的方法,如果有类想要使用这个方法,直接可以实现MyInterfaceSon这个类。 但是这样用的话,以后还是会出现想用的问题

  1. public interface MyInterfaceSon extends MyInterface{
  2. }

那我们就可以在接口中使用默认方法,如下所示,当我们添加一个默认方法后,实现MyInterface的类可以选择实现方法show3,也可以选择不实现,很人性化

  1. public interface MyInterface {
  2. void show1();
  3. void show2();
  4. public default void show3(){
  5. }
  6. }

总结来说:方法的升级不会破坏现有的代码

1.2.2 默认方法的使用

public default 返回值类型 方法名(参数列表){ }

其中 public是可以省略的

  1. public interface MyInterface {
  2. void show1();
  3. void show2();
  4. public default void show3(){
  5. // 方法体
  6. }
  7. }

当我们给MyInterface接口多加了一个default方法后,下面的实现类并没有报错

当我们子类实现show3方法的时候,发现没有default这个关键字了,一定要注意

1.3 静态方法

静态方法只能通过接口名调用,不能通过实现类名或者对象名调用

public static 返回值类型 方法名(参数列表){}

public可以省略

  1. public static void show(){
  2. }

1.3.1 静态方法的使用

  1. public interface Inter {
  2. void show();
  3. default void method(){
  4. System.out.println("Inter中的默认方法执行了");
  5. }
  6. public static void test(){
  7. System.out.println("Inter中的静态方法执行了");
  8. }
  9. }
  1. public class InterImpl implements Inter{
  2. @Override
  3. public void show() {
  4. System.out.println("show方法执行了");
  5. }
  6. }

然后我们发现我们掉用不了静态的test方法

静态方法只能在包含接口类上调用
Static method may be invoked on containing interface class only

为什么只能通过类来调用呢?
假设 InterImpl这个实现类实现了好几个接口,并且每个接口中都有test静态方法,那如果此时再通过实例对象调用,编译器将不会知道调用哪个接口的test方法

1.4 私有方法(Java9)

1.4.1 接口中的私有方法

Java 9 中新增了带方法体的私有方法,这其实在Java 8中就埋下了伏笔:Java 8允许在接口中定义带方法体的默认方法和静态方法。

这样可能会引发一个问题:当两个默认方法或者静态方法中包含一段相同的代码实现时,程序必然考虑将这段代码抽取成一个共性的方法,而这个共性方法是不需要让别人使用的,因此用私有给隐藏起来,这就是Java 9增加私有方法的必然性

格式:

private 返回值类型 方法名(参数列表){}

private static 返回值类型 方法名(参数列表){}

示例:

  1. private void show(){}
  2. private static void method(){}

1.4.2 接口中私有方法的使用

一定要注意!!!!

默认方法可以调用私有静态方法,但是静态方法无法调用私有默认方法

自我理解出现这种情况的原因:
其实说白了和这个根本没有关系,其实和 方法是不是静态方法或者是实例方法有关。
我为什么这么说呢,我解释一下

静态方法什么时候被加载呢?
当然是在class文件被加载的时候,也就是说在方法区就被加载了

实例方法什么时候被加载?
在程序运行过程中类实例化后才会存在。

那这样说来就很清晰了,即我们不实例化我们也是可以使用静态方法的,但是不可以使用实例方法。 那如果我们在静态方法中调用了实例方法,但我没有对此类进行实例化,那肯定是不符合要求的呀,你 没有实例化怎么能在静态方法中调用实例方法呢?

  1. public class InterImpl implements Inter{
  2. }
  1. public interface Inter {
  2. default void show1() {
  3. System.out.println("show1开始执行");
  4. // 抽取下面的三行
  5. // System.out.println("初级工程师");
  6. // System.out.println("中级工程师");
  7. // System.out.println("高级工程师");
  8. show();
  9. System.out.println("show1结束执行");
  10. }
  11. default void show2() {
  12. System.out.println("show2开始执行");
  13. // 抽取下面的三行
  14. // System.out.println("初级工程师");
  15. // System.out.println("中级工程师");
  16. // System.out.println("高级工程师");
  17. show();
  18. System.out.println("show2结束执行");
  19. }
  20. private void show() {
  21. System.out.println("初级工程师");
  22. System.out.println("中级工程师");
  23. System.out.println("高级工程师");
  24. }
  25. static void method1() {
  26. System.out.println("method1开始执行");
  27. // System.out.println("初级工程师");
  28. // System.out.println("中级工程师");
  29. // System.out.println("高级工程师");
  30. method();
  31. System.out.println("method1结束执行");
  32. }
  33. static void method2() {
  34. System.out.println("method2开始执行");
  35. // System.out.println("初级工程师");
  36. // System.out.println("中级工程师");
  37. // System.out.println("高级工程师");
  38. method()
  39. System.out.println("method2结束执行");
  40. }
  41. private static void method() {
  42. System.out.println("初级工程师");
  43. System.out.println("中级工程师");
  44. System.out.println("高级工程师");
  45. }
  46. }

  1. public class InterDemo {
  2. public static void main(String[] args) {
  3. // 按照多态的方式创建对象并使用
  4. Inter i = new InterImpl();
  5. i.show1();
  6. System.out.println("----------");
  7. i.show2();
  8. System.out.println("----------");
  9. Inter.method1();
  10. System.out.println("----------");
  11. Inter.method2();
  12. }
  13. }

二、引用

对lambda表达式不熟悉可以看下面的文章
(45条消息) JDK 8新特性——Lambda表达式_我爱布朗熊的博客-CSDN博客

2.1 体验方法引用

在使用Lambda表达式的时候,我们实际上传递进去的代码就是一种解决方法:拿参数做操作

那么考虑一种情况:如果我们在Lambda中所指定的操作方案,已经有地方存在相同的方案,那是否还有必要再重写逻辑呢?那我们如何使用已经存在的解决方案的呢?

  1. @FunctionalInterface
  2. public interface Printable {
  3. void printString(String s);
  4. }
  1. public class PrintableDemo {
  2. public static void main(String[] args) {
  3. // 第一种写法: lambda表达式
  4. usePrintable( (s -> System.out.println(s)));
  5. System.out.println("****************");
  6. // 第二种写法:lambda表达式
  7. Printable printable = (s) -> {
  8. System.out.println(s);
  9. };
  10. usePrintable(printable);
  11. System.out.println("****************");
  12. // 第三种写法:方法引用符 ::
  13. // System.out是一个对象,我们要调用此对象下的println方法
  14. usePrintable(System.out::println);
  15. }
  16. private static void usePrintable(Printable p){
  17. p.printString("爱生活爱Java");
  18. }
  19. }

2.2 方法引用符

如果使用Lambda,那么根据"可推导就是可省略"的原则,无需指定参数类型,也无需指定的重载形式,它们都将被自动推导。如果使用方法引用,也是同样可以根据上下文进行推导

  • :: 双冒号,引用运算符,而它所在的表达式被称为方法引用

usePrintable(System.out::println);

直接使用System.out中的println方法来取代Lambda,代码更加的简洁

  • 对比一下lambda表达式

usePrintable( (s -> System.out.println(s)));

分析: 拿到参数s之后通过Lambda表达式,传递给System.out.println方法去处理

2.3 引用类方法(静态方法)

  • 格式: 类名::静态方法

  • 范例: Integer::parseInt

Integer类的方法,public static int parseInt(String s) 将此String转换为int类型的数据

  1. @FunctionalInterface
  2. public interface Converter {
  3. int convert(String s);
  4. }
  1. public class ConverterDemo {
  2. public static void main(String[] args) {
  3. // 1.匿名内部类表达式
  4. useConverter(new Converter() {
  5. @Override
  6. public int convert(String s) {
  7. return Integer.parseInt(s);
  8. }
  9. });
  10. // 2.lambda表达式
  11. // Converter converter = (String s) -> {
  12. // return Integer.parseInt(s);
  13. // };
  14. // useConverter(converter);
  15. useConverter((String s) -> {
  16. return Integer.parseInt(s);
  17. });
  18. // 3.引用类方法
  19. // lambda表达式被类方法替代的时候,它的形式参数全部传递给静态方法作为参数
  20. useConverter(Integer::parseInt);
  21. }
  22. private static void useConverter(Converter c){
  23. int number = c.convert("666");
  24. System.out.println(number);
  25. }
  26. }

2.4 引用对象的实例方法(成员方法)

其实就是引用类中的成员方法、

  • 格式: 对象::成员方法

  • 范例: "HelloWord"::toUpperCase

String类中的方法:public String toUpperCase() 将此String所有字符转换成大写

  1. public class PrinterDemo {
  2. public static void main(String[] args) {
  3. // 1.Lambda表达式
  4. userPrinter((String s) ->{
  5. String result = s.toUpperCase();
  6. System.out.println(result);
  7. });
  8. // 2.引用成员方法
  9. PrintString printString = new PrintString();
  10. userPrinter(printString::printUpper);
  11. }
  12. private static void userPrinter(Printer p) {
  13. p.printUpperCase("HelloWord");
  14. }
  15. }

  1. public interface Printer {
  2. void printUpperCase(String s);
  3. }

  1. public class PrintString {
  2. public void printUpper(String s){
  3. System.out.println(s.toUpperCase());
  4. }
  5. }

2.5引用类的实例方法

其实就是引用类中的成员方法

  • 格式: 类名::成员方法

  • 范例: String::substring

String类中的方法:public String substring(int beginIndex, int endIndex) 从beginIndex开始到endIndex结束,截取字符串,返回一个子串,子串的长度为endIndex-beginIndex

  1. public interface MyString {
  2. String mySubString(String s,int x,int y);
  3. }

  1. public class MyStringDemo {
  2. public static void main(String[] args) {
  3. // 1.lambda表达式的形式
  4. useMyString((s,x,y)->{
  5. String substring = s.substring(x, y);
  6. return substring;
  7. });
  8. // 2.方法引用
  9. useMyString(String::substring);
  10. }
  11. public static void useMyString(MyString my){
  12. String s = my.mySubString("HelloWorld", 2, 5);
  13. System.out.println(s);
  14. }
  15. }

2.6 引用构造器

引用构造器,其实就是引用构造方法

  • 格式: 类名:: new

  • 范例: Student::new

三、函数式接口

3.1 概述

函数式接口: 有且仅有一个抽象方法的接口

Java中的函数式变成体现就是lambda表达式,所以函数式接口就是可以适用于Lambda使用的接口,只有确保接口中有且仅有一个抽象方法,Java中的Lambda才能顺利地进行推导

  1. public interface MyInterface {
  2. void show();
  3. }

  1. public class MyInterfaceDemo {
  2. public static void main(String[] args) {
  3. MyInterface my = ()->{
  4. System.out.println("函数式接口");
  5. };
  6. my.show();
  7. }
  8. }

但是对于MyInterface接口,我们知道其有一个方法,知道是函数式接口,那万一以后有人再修改接口,新增加抽象方法,那岂不是我们在Demo中的程序无法运行了?

答案: 是的!

为了避免这种情况,我们可以在接口上使用@FunctionalInterface注解,用意是标注此接口为函数式接口

  1. @FunctionalInterface
  2. public interface MyInterface {
  3. void show();
  4. }

3.2 函数式接口作为方法的参数

  1. public class RunnableDemo {
  2. public static void main(String[] args) {
  3. // 1.匿名内部类
  4. startThread(new Runnable() {
  5. @Override
  6. public void run() {
  7. System.out.println(Thread.currentThread().getName()+"线程启动了");
  8. }
  9. });
  10. // 2.lambda表达式
  11. startThread(()->{
  12. System.out.println(Thread.currentThread().getName()+"线程启动了");
  13. });
  14. // 2.1更清晰的写法
  15. Runnable runnable =()->{
  16. System.out.println(Thread.currentThread().getName()+"线程启动了");
  17. };
  18. startThread(runnable);
  19. }
  20. // Runnable 接口是函数式接口
  21. public static void startThread(Runnable r){
  22. // Thread t = new Thread(r);
  23. // t.start();
  24. new Thread(r).start();
  25. }
  26. }

3.3 函数式接口作为方法的返回值

很明显,我们的返回值类型是一个函数式接口

  1. public class ComparatorDemo {
  2. public static void main(String[] args) {
  3. ArrayList<String> arrayList = new ArrayList<>();
  4. arrayList.add("cccc");
  5. arrayList.add("aa");
  6. arrayList.add("b");
  7. arrayList.add("saff");
  8. System.out.println("排序前:"+arrayList);
  9. // 排序
  10. Collections.sort(arrayList,getComparator());
  11. System.out.println("排序后:"+arrayList);
  12. }
  13. private static Comparator<String> getComparator(){
  14. Comparator<String> comp = new Comparator<String>() {
  15. @Override
  16. public int compare(String o1, String o2) {
  17. return o1.length()-o2.length();
  18. }
  19. };
  20. return comp;
  21. // 比较的逻辑也能使用Lambda表达式的形式
  22. // return (s1,s2)->{
  23. // return s1.length()-s2.length();
  24. // };
  25. }
  26. }

3.4 常用的函数式接口

3.4.1 Supplier

Supplier<T>:包含一个无参的方法

  • T get(): 获得结果

  • 该方法不需要参数,它会按照某种实现逻辑(由Lambda表达式实现)返回一个数据

  • Supplier<T> 接口也被称为生产型接口,如果我们指定了接口的泛型是什么类型,那么接口中的get方法就会生产什么类型的数据供我们使用

  1. public class SupplierDemo {
  2. public static void main(String[] args) {
  3. // 写法1:
  4. String string1 = getString(() -> {
  5. return "林青霞";
  6. });
  7. System.out.println(string1);
  8. // 写法2:
  9. Supplier<String> supplier = ()->{
  10. return "林青霞";
  11. };
  12. String string2 = getString(supplier);
  13. System.out.println(string2);
  14. }
  15. // 定义一个方法,返回字符串数据
  16. private static String getString(Supplier<String> supplier){
  17. return supplier.get();
  18. }
  19. }

3.4.1.1 Supplier接口获取最大值
  1. public class SupplierTest {
  2. public static void main(String[] args) {
  3. // 定义一个int数组
  4. int[] arr= {19,50,28,37,46};
  5. int maxNum = getMax(() -> {
  6. int max = arr[0];
  7. for (int i = 1; i < arr.length; i++) {
  8. if (arr[i] > max) {
  9. max = arr[i];
  10. }
  11. }
  12. return max;
  13. });
  14. System.out.println(maxNum);
  15. }
  16. private static int getMax(Supplier<Integer> supplier){
  17. return supplier.get();
  18. }
  19. }

3.4.2 Consumer接口 消费型接口

Consumer<T> 包含两个方法

Consumer接口也称为消费型接口,它消费的数据的数据类型由泛型指定

  • void accept(T t): 对给定的参数执行此操作

  • default Consumer<T> andThen(Consumer after): 返回一个组合的Consumer,依次执行此操作,然后执行after操作

  1. public class ConsumerDemo {
  2. public static void main(String[] args) {
  3. operatorString("林青霞", (String s) -> {
  4. System.out.println(s);
  5. });
  6. }
  7. private static void operatorString(String name, Consumer<String> consumer) {
  8. consumer.accept(name);
  9. }
  10. }

3.4.2.1 Consumer—按要求打印信息
  • String[] strArray={"林青霞,30" , "张曼玉,35" , "王祖贤,33" };

  • 字符串数组中有多条信息,请按照格式:"姓名:xx,年龄:xx"的格式将信息打印出来

  • 要求:

把打印姓名的动作作为第一个Consumer接口的Lambda实例

把打印年龄的动作作为第二个Consumer接口的Lambda实例

将两个Consumer接口按照顺序组合到一起使用

  1. public class ConsumerTest {
  2. public static void main(String[] args) {
  3. String[] strArray={"林青霞,30" , "张曼玉,35" , "王祖贤,33" };
  4. printInfo(strArray,(String str)->{
  5. String name = str.split(",")[0];
  6. System.out.println("姓名:"+name);
  7. },(String str)->{
  8. int age = Integer.parseInt(str.split(",")[1]);
  9. System.out.println("年龄:"+age);
  10. });
  11. }
  12. private static void printInfo(String[] strArry, Consumer<String> con1,Consumer<String> con2){
  13. for (String str: strArry){
  14. con1.andThen(con2).accept(str);
  15. }
  16. }
  17. }

3.4.3 Predicate

表示对一个参数进行判断的,返回一个布尔值

下图是Api文档中对Predicate接口方法的描述

  • Predicate<T>:常用的四个方法

  • boolean test(T t):对给定的参数进行判断(判断罗辑由Lambda表达式实现),返回一个布尔值

  • default Predicate<T>negate0:返回一个逻辑的否定,对应逻辑非default

  • Predicate<T>and(Predicate other): 返回一个组合判断,对应短路与

  • defaultPredicate<T>or(Predicate other): 返回一个组合判断,对应短路或

3.4.3.1 Predicate<T> 接口通常用于判断参数是否满足指定的条件
  1. public class PredicateDemo01 {
  2. public static void main(String[] args) {
  3. boolean b = checkString("hello", (String s) -> {
  4. return s.length() > 8;
  5. });
  6. System.out.println(b);
  7. }
  8. private static boolean checkString(String s, Predicate<String> pre){
  9. return pre.test(s);
  10. }
  11. }

3.4.3.2 negate逻辑非的运算
  1. private static boolean checkString(String s, Predicate<String> pre){
  2. // return !pre.test(s); 这种情况是我们之前的饿用法
  3. return pre.negate().test(s);
  4. }

3.4.3.3 组合判断,对应短路与
  1. public class PredicateDemo01 {
  2. public static void main(String[] args) {
  3. boolean b = checkString("hello",
  4. (String s) -> {
  5. return s.length() > 8;
  6. },
  7. (String s) -> {
  8. return s.length() <15;
  9. });
  10. System.out.println(b);
  11. }
  12. // 同一个字符串给出两个不同的判断条件,最后把这两个判断的结果做逻辑与运算的结果作为最终的结果
  13. private static boolean checkString(String s, Predicate<String> pre1, Predicate<String> pre2) {
  14. //
  15. // boolean b1 = pre1.test(s);
  16. // boolean b2 = pre2.test(s);
  17. // boolean b = b1 && b2;
  18. // return b;
  19. return pre1.and(pre2).test(s);
  20. }
  21. }

3.4.3.4 组合判断,对应短路或
  1. private static boolean checkString(String s, Predicate<String> pre1, Predicate<String> pre2) {
  2. return pre1.or(pre2).test(s);
  3. }

3.4.3.5 筛选满足条件的数据
  • String[] strArray={"林青霞,30","柳岩,34","张曼玉,35","貂蝉,31","王祖贤,33"};

  • 字符串数组中有多条信息,请通过Predicate接口的拼装将符合要求的字符审筛选到集合ArraList中,并遍历ArrayList

  • 集合同时满足如下要求:姓名长度大于2;年龄大于33

  1. public class PredicateDemo02 {
  2. public static void main(String[] args) {
  3. String[] strArray = {"林青霞,30", "柳岩,34", "张曼玉,35", "貂蝉,31", "王祖贤,33"};
  4. ArrayList<String> arrayList = myFilter(strArray,
  5. (String s) -> {
  6. return s.split(",")[0].length() > 2;
  7. }, (String s) -> {
  8. return Integer.parseInt( s.split(",")[1])>33;
  9. });
  10. System.out.println(arrayList);
  11. }
  12. private static ArrayList<String> myFilter(String[] strArray, Predicate<String> pre1, Predicate<String> pre2) {
  13. ArrayList<String> arrayList = new ArrayList<>();
  14. // 便利数组
  15. for (String str : strArray) {
  16. if (pre1.and(pre2).test(str)) {
  17. arrayList.add(str);
  18. }
  19. }
  20. return arrayList;
  21. }
  22. }

3.4.4 Function

Function<T,R>接口通常用于对参数进行处理,转换(处理逻辑由Lambda表达式实现),然后返回一个新的值

  • R apply(T t): 将此函数应用于给定的参数

  • default<V> Function andThen(Function after): 返回一个组合函数,首先将该函数应用于输入,然后将after函数应用于结果

  1. public class FunctionDemo {
  2. public static void main(String[] args) {
  3. convert("100",(String s)->{
  4. return Integer.parseInt(s);
  5. });
  6. }
  7. // 将String转化为integer
  8. private static void convert(String s, Function<String, Integer> function){
  9. Integer apply = function.apply(s);
  10. System.out.println(apply);
  11. }
  12. }

3.4.4.1 按照指定要求操作数据
  • String s="林青霞,30"

  • 请按照我指定的要求进行操作:

  • 1:将字符串截取得到数字年龄部分

  • 2:将上一步的年龄字特串转换成为int类型的数据

  • 3:将上一步的int数据加70,得到一个int结果,在控制台输出请通过Function接口来实现函数拼接

  1. public class FunctionDemo {
  2. public static void main(String[] args) {
  3. convert("林青霞,30",
  4. (String s) -> {
  5. // 提取出30
  6. return s.split(",")[1];
  7. },
  8. // 将字符串转换成Integer
  9. s1 -> {
  10. return Integer.parseInt(s1);
  11. },
  12. // 将这个数加70
  13. s2 -> {
  14. return s2+70;
  15. }
  16. );
  17. }
  18. // 将String转化为integer
  19. private static void convert(String s, Function<String, String> function1, Function<String, Integer> function2, Function<Integer, Integer> function3) {
  20. // Integer apply = function1.apply(s);
  21. // System.out.println(apply);
  22. Integer integer = function1.andThen(function2).andThen(function3).apply(s);
  23. System.out.println(integer);
  24. }
  25. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/53242
推荐阅读
相关标签
  

闽ICP备14008679号