jdk 1.8新特性
1.default关键字:接口可以加普通方法
接口类里用default修饰,添加普通方法
interface Demo{ /** *接口里原来的属性和抽象方法.... */ //用default修饰添加普通方法 default double sqrt(int a) { return Math.sqrt(a); } }
2.Lambda表达式:匿名内部类用lambda表达式替代
匿名内部类
List<String> names = Arrays.asList("peter", "anna", "mike", "xenia"); Collections.sort(names, new Comparator<String>() { @Override public int compare(String a, String b) { return b.compareTo(a); } });
转化为lambda表达式
Collections.sort(names, (String a, String b) -> {
return b.compareTo(a);
});
如果只有一行代码,可以把{}去掉。
3.函数式接口是指仅仅只包含一个抽象方法的接口。
为什么这么做呢?答案就是为了更好的支持lambda表达式(不如说为了更好的支持函数式编程),像这样的接口,可以被隐式转换为lambda表达式。
举个例子:
//为了不容易出错,加注解 @FunctionalInterface @FunctionalInterface public interface function1{ public void method1(); //注意函数式接口只能有一个抽象方法,但是default修饰的普通方法不是抽象方法,所以可以有很多个 default void defaultMethod() { System.out.println("我又不是抽象方法"); } }
想一下,一个接口只能定义一个抽象方法,就变成了函数式接口,那么是不是特别容易出错呢,所以为了不出错,加注解@FunctionalInterface,加了注解之后表示这个是函数式接口,只能有一个抽象方法。
注意:因为接口里default修饰的普通方法不是抽象方法,所以函数式接口里可以有很多个default修饰的普通方法
4.方法引用
学习方法引用之前先回忆一下对象引用:Person p = new Person();有人说p是一个对象,其实并不是真正的对象,它只是对象的引用。那么方法引用实际上同对象引用一样,方法引用也不过是将已存在的方法添加一个引用。
有以下四种形式的方法引用:
类型 | 示例 |
---|---|
引用静态方法 | ContainingClass::staticMethodName |
引用某个对象的实例方法 | containingObject::instanceMethodName |
引用某个类型的任意对象的实例方法 | ContainingType::methodName |
引用构造方法 | ClassName::new |
1).静态方法引用
格式:类 :: 静态方法名
package com.hc360.test;
//函数式接口才能方法引用 @FunctionalInterface interface IMessage{ public String copy(char[] data); } public class Demo { public static void main(String[] args) { //String类的静态方法public static String copyValueOf(char[] data) IMessage msg = String :: copyValueOf; char[] c = {'a','b'}; System.out.println(msg.copy(c)); } }
2)对象实例方法引用
格式:对象 :: 普通方法
package com.hc360.test; @FunctionalInterface interface IMessage{ public String myReplace(String target, String replacement); } public class Demo { public static void main(String[] args) { //String类的方法public String replace(CharSequence target,CharSequence replacement) IMessage msg = "I am so bad" :: replace; String result = msg.myReplace("bad", "happy"); System.out.println(result); } }
3)构造函数引用
格式:类 :: new
package com.hc360.test; @FunctionalInterface interface IMessage{ public Book create(String title, double price); } class Book{ private String title; private double price; public Book(String title,double price) { this.title = title; this.price = price; } @Override public String toString() { return "书名:"+this.title + ",价格:"+this.price; } } public class Demo { public static void main(String[] args) { //String类的方法public String replace(CharSequence target,CharSequence replacement) IMessage msg = Book :: new; Book book = msg.create("bad", 12.56); System.out.println(book); } }