文章目录
Java 8是Java自Java 5(发布于2004年)之后的最重要的版本。这个版本包含语言、编译器、库、工具和JVM等方面的十多个新特性。 该章节为语言的新特性。
一、Lambda表达式
Lambda 表达式,也可称为闭包,它是推动 Java 8 发布的最重要新特性。
Lambda 允许把函数作为一个方法的参数(函数作为参数传递进方法中)。
使用 Lambda 表达式可以使代码变的更加简洁紧凑。
能够接收Lambda表达式的参数类型,是一个只包含一个方法的接口。只包含一个方法的接口称之为“函数接口”。即使用Lambda表达式,需先声明一个只包含一个方法的接口。
应用场景: 创建匿名方法,作为一个方法的参数。
语法
(parameters) -> expression
或
(parameters) ->{ statements; }
- 可选类型声明:不需要声明参数类型,编译器可以统一识别参数值。
- 可选的参数圆括号:一个参数无需定义圆括号,但多个参数需要定义圆括号。
- 可选的大括号:如果主体包含了一个语句,就不需要使用大括号。
- 可选的返回关键字:如果主体只有一个表达式返回值则编译器会自动返回值,大括号需要指定明表达式返回了一个数值。
lambda中如果引用this,那么this指针是包装类,即lambda被调用的类;而内部类中,则是指内部类。
Lamdba表达式简单实例
public class FunctionInterfaceTest {
/**
* 函数接口
*/
public interface FunctionInterface{
/**
* @param a
* @param b
* @return
*/
int add(int a, int b);
}
public static void main(String[] args) {
FunctionInterface functionInterface = (int a, int b)
-> { return a * b; };
int c = functionInterface.add(1, 3);
System.out.println(c);
}
}
// 1. 不需要参数,返回值为 5
() -> 5
// 2. 接收一个参数(数字类型),返回其2倍的值
x -> 2 * x
// 3. 接受2个参数(数字),并返回他们的差值
(x, y) -> x – y
// 4. 接收2个int型整数,返回他们的和
(int x, int y) -> x + y
// 5. 接受一个 string 对象,并在控制台打印,不返回任何值(看起来像是返回void)
(String s) -> System.out.print(s)
public class Java8Tester {
public static void main(String args[]){
Java8Tester tester = new Java8Tester();
// 类型声明
MathOperation addition = (int a, int b) -> a + b;
// 不用类型声明
MathOperation subtraction = (a, b) -> a - b;
// 大括号中的返回语句
MathOperation multiplication = (int a, int b) -> { return a * b; };
// 没有大括号及返回语句
MathOperation division = (int a, int b) -> a / b;
System.out.println("10 + 5 = " + tester.operate(10, 5, addition));
System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));
System.out.println("10 / 5 = " + tester.operate(10, 5, division));
// 不用括号
GreetingService greetService1 = message ->
System.out.println("Hello " + message);
// 用括号
GreetingService greetService2 = (message) ->
System.out.println("Hello " + message);
greetService1.sayMessage("Runoob");
greetService2.sayMessage("Google");
}
interface MathOperation {
int operation(int a, int b);
}
interface GreetingService {
void sayMessage(String message);
}
private int operate(int a, int b, MathOperation mathOperation){
return mathOperation.operation(a, b);
}
}
使用 Lambda 表达式需要注意以下两点:
- Lambda 表达式主要用来定义行内执行的方法类型接口,例如,一个简单方法接口。在上面例子中,我们使用Lambda表达式来定义FunctionInterface接口的方法。然后我们定义了add的执行。
- Lambda 表达式免去了使用匿名方法的麻烦,并且给予Java简单但是强大的函数化的编程能力。
变量作用域
ambda 表达式只能引用标记了 final 的外层局部变量,这就是说不能在 lambda 内部修改定义在域外的局部变量,否则会编译错误。
public class Java8Tester {
final static String salutation = "Hello! ";
public static void main(String args[]){
GreetingService greetService1 = message ->
System.out.println(salutation + message);
greetService1.sayMessage("Runoob");
}
interface GreetingService {
void sayMessage(String message);
}
}
lambda 表达式的局部变量可以不用声明为 final,但是必须不可被后面的代码修改(即隐性的具有 final 的语义)
int num = 1;
Converter<Integer, String> s = (param) ->
System.out.println(String.valueOf(param + num));
s.convert(2);
num = 5;
//报错信息:Local variable num defined in an enclosing scope must be final or effectively
final
在 Lambda 表达式当中不允许声明一个与局部变量同名的参数或者局部变量。
String first = "";
Comparator<String> comparator = (first, second) ->
Integer.compare(first.length(), second.length()); //编译会出错
二、方法引用
方法引用通过方法的名字来指向一个方法。
方法引用可以使语言的构造更紧凑简洁,减少冗余代码。
方法引用使用一对冒号 :: ,类名::方法名
应用场景: 调用了一个已存在的方法
四种形式的方法引用:
类型 | 示例 |
---|---|
引用静态方法 | 类名称::静态方法名称 |
引用某个对象的实例的普通方法 | 实例对象::普通方法名称 |
引用某个类型的任意对象的实例的普通方法 | 特定类::方法名称 |
引用构造器 | 类名称::new |
引用静态方法
/**
* 实现方法的引用接口
*
* @param <P>引用方法的参数类型
* @param <R>引用方法的返回类型
*/
interface MyInterface<P, R> {
public R function(P p);//和String.valueOf(int x)类似
}
interface MyInterface1 {
String function(Integer a);
}
public class Main {
public static void test(MyInterface1 myInterface1) {
String result = myInterface1.function(2000);
System.out.println(result + " --");
}
public static void main(String[] args) {
//匿名内部类实现
test(new MyInterface1() {
@Override
public String function(Integer a) {
return String.valueOf(a);
}
});
//Lamda表达式实现
test((a) -> String.valueOf(a));
//方法引用实现:引用类的静态方法
MyInterface<Integer, String> msg = String::valueOf;
String str = msg.function(2000);
System.out.println(str);
// 将 System.out::println 方法作为静态方法来引用。
List names = new ArrayList();
names.add("Google");
names.add("Runoob");
names.add("Taobao");
names.add("Baidu");
names.add("Sina");
names.forEach(System.out::println);
}
}
引用某个对象的实例的普通方法
如:String类中的toUpperCase()方法:public String toUpperCase();
这个方法没有参数,但是有返回值,并且这个方法一定要在有实例化对象的时候才可以调用。
@FunctionalInterface //此为函数式接口,只能够定义一个方法
interface MyInterface2<R> {
public R upper();
}
public class Main1 {
public static void main(String[] args) {
String str = new String("hello");
MyInterface2<String> msg = str::toUpperCase;
//调用upper方法,就相当于调用toUpperCase方法
System.out.println(msg.upper());
}
}
为了保证被引用的接口里面只能够定义一个方法,就要在接口上加以限制,使用@FunctionalInterface 注解。
引用某个类型的任意对象的实例的普通方法
比如:String类中的compareTo(String str1,String str2)方法 public int compareTo(String anotherString);
如果要进行比较的话,比较的形式:字符串1对象.compareTo(字符串2对象),要准备两个参数。
@FunctionalInterface//此为函数式接口,只能够定义一个方法
interface MyInterface3<P> {
public int compare(P p1, P p2);
}
public class Main2 {
public static void main(String[] args) {
MyInterface3<String> msg = String::compareTo;
System.out.println(msg.compare("A", "B"));
}
}
与之前相比,方法引用前不需要再定义对象,而是可以理解为将对象定义在了参数中。
引用构造方法
@FunctionalInterface //此为函数式接口,只能够定义一个方法
interface MyInterface4<C> {
public C person(String n, int a);
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "姓名:" + this.name + ",年龄:" + this.age;
}
}
public class Main3 {
public static void main(String[] args) {
MyInterface4<Person> msg = Person::new;//引用构造方法
Person person = msg.person("小明", 20);
System.out.println(person);
}
}
三、函数式接口
函数式接口(Functional Interface)就是一个有且仅有一个抽象方法,但是可以有多个非抽象方法的接口。
函数式接口可以被隐式转换为 lambda 表达式。
Lambda 表达式和方法引用(实际上也可认为是Lambda表达式)上。
语法
如定义了一个函数式接口如下:
@FunctionalInterface
interface GreetingService
{
void sayMessage(String message);
}
那么就可以使用Lambda表达式来表示该接口的一个实现(注:JAVA 8 之前一般是用匿名类实现的):
GreetingService greetService1 = message
-> System.out.println("Hello " + message);
函数式接口示例
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class Main5 {
public static void main(String args[]){
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
// Predicate<Integer> predicate = n -> true
// n 是一个参数传递到 Predicate 接口的 test 方法
// n 如果存在则 test 方法返回 true
System.out.println("输出所有数据:");
// 传递参数 n
eval(list, n->true);
// Predicate<Integer> predicate1 = n -> n%2 == 0
// n 是一个参数传递到 Predicate 接口的 test 方法
// 如果 n%2 为 0 test 方法返回 true
System.out.println("输出所有偶数:");
eval(list, n-> n%2 == 0 );
// Predicate<Integer> predicate2 = n -> n > 3
// n 是一个参数传递到 Predicate 接口的 test 方法
// 如果 n 大于 3 test 方法返回 true
System.out.println("输出大于 3 的所有数字:");
eval(list, n-> n > 3 );
}
public static void eval(List<Integer> list, Predicate<Integer> predicate) {
for(Integer n: list) {
if(predicate.test(n)) {
System.out.println(n + " ");
}
}
}
}
函数式接口可以对现有的函数友好地支持 lambda。
JDK 1.8 之前已有的函数式接口:
java.lang.Runnable
java.util.concurrent.Callable
java.security.PrivilegedAction
java.util.Comparator
java.io.FileFilter
java.nio.file.PathMatcher
java.lang.reflect.InvocationHandler
java.beans.PropertyChangeListener
java.awt.event.ActionListener
javax.swing.event.ChangeListener
JDK 1.8 新增加的函数接口:
java.util.function
四、默认方法
认方法就是接口可以有实现方法,而且不需要实现类去实现其方法。
我们只需在方法名前面加个 default 关键字即可实现默认方法。
为什么要有这个特性?
首先,之前的接口是个双刃剑,好处是面向抽象而不是面向具体编程,缺陷是,当需要修改接口时候,需要修改全部实现该接口的类,目前的 java 8 之前的集合框架没有 foreach 方法,通常能想到的解决办法是在JDK里给相关的接口添加新的方法及实现。然而,对于已经发布的版本,是没法在给接口添加新方法的同时不影响已有的实现。所以引进的默认方法。他们的目的是为了解决接口的修改与现有的实现不兼容的问题。
语法
示例:
package java.util.function;
import java.util.Objects;
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}
default Predicate<T> negate() {
return (t) -> !test(t);
}
default Predicate<T> or(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
}
static <T> Predicate<T> isEqual(Object targetRef) {
return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
}
多个默认方法
一个接口有默认方法,考虑这样的情况,一个类实现了多个接口,且这些接口有相同的默认方法,以下实例说明了这种情况的解决方法:
public interface Vehicle {
default void print(){
System.out.println("我是一辆车!");
}
}
public interface FourWheeler {
default void print(){
System.out.println("我是一辆四轮车!");
}
}
第一个解决方案是创建自己的默认方法,来覆盖重写接口的默认方法:
public class Car implements Vehicle, FourWheeler {
default void print(){
System.out.println("我是一辆四轮汽车!");
}
}
第二种解决方案可以使用 super 来调用指定接口的默认方法:
public class Car implements Vehicle, FourWheeler {
public void print(){
Vehicle.super.print();
}
}
静态默认方法
Java 8 的另一个特性是接口可以声明(并且可以提供实现)静态方法。例如:
public interface Vehicle {
default void print(){
System.out.println("我是一辆车!");
}
// 静态方法
static void blowHorn(){
System.out.println("按喇叭!!!");
}
}
五、重复注解
之前注解有一个很大的限制是:在同一个方法或类上同种注解只能声明一次。Java 8打破了这个限制,引入了重复注解的概念,允许在同一个地方多次使用同一个注解。
在Java 8中使用@Repeatable注解定义重复注解,实际上,这并不是语言层面的改进,而是编译器做的一个trick,底层的技术仍然相同。可以利用下面的代码说明:
示例
import java.lang.annotation.*;
import java.lang.reflect.Method;
public class Java8Test {
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface StudentList{
Student[] value();
}
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(StudentList.class)
@interface Student{
String name();
int age();
}
//写法一
@Student(age = 17, name = "张三")
@Student(age = 18, name = "李四")
public void test(){
}
//写法二
@StudentList({@Student(age = 17, name = "张三"),@Student(age = 18, name = "李四")})
public void test1() {
}
public static void main(String[] args) {
//获取值
Class<?> clazz = Java8Test.class;
Method [] methods = clazz.getMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
StudentList studentList = method.getAnnotation(StudentList.class);
if(studentList != null){
Student[] values = studentList.value();
System.out.println(method.getName());
for (Student stu : values) {
System.out.println(stu.name());
System.out.println(stu.age());
}
}
}
}
}
六、更好的类型推断
Lambda 的类型是从 Lambda 的上下文推断出来的。
上下文中 Lambda 表达式需要的类型称为 目标类型。
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
public class Main6 {
public static void main(String[] args) {
ArrayList<Apple> apples = new ArrayList<>();
apples.add(new Main6().new Apple("品种1", 140));
apples.add(new Main6().new Apple("品种2", 240));
//Lamdba通过类型推断
List<Apple> result = filter(apples, a -> a.getWeight() > 150);
for (Apple apple : result) {
System.out.println(apple);
}
}
public static List<Apple> filter(List<Apple> inventory, Predicate<Apple> p) {
ArrayList<Apple> goods = new ArrayList<Apple>();
for (int i = 0; i < inventory.size(); i++) {
Apple apple = inventory.get(i);
Boolean flag = p.test(apple);
if (flag) {
goods.add(apple);
}
}
return goods;
}
class Apple {
public Apple(String type, int weight) {
this.weight = weight;
this.type = type;
}
private int weight;
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
@Override
public String toString() {
return "type="+type+" weight="+weight;
}
}
}
七、注解类型拓展
Java 8新增了ElementType.TYPE_USER和ElementType.TYPE_PARAMETER两个注解类型,用于描述注解的使用场景。
使得注解几乎可以使用在任何元素上:局部变量、接口类型、超类和接口实现类,甚至可以用在函数的异常定义上。
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.Collection;
public class Annotations {
@Retention( RetentionPolicy.RUNTIME )
@Target( { ElementType.TYPE_USE, ElementType.TYPE_PARAMETER } )
public @interface NonEmpty {
}
public static class Holder< @NonEmpty T > extends @NonEmpty Object {
public void method() throws @NonEmpty Exception {
}
}
@SuppressWarnings( "unused" )
public static void main(String[] args) {
final Holder< String > holder = new @NonEmpty Holder< String >();
@NonEmpty Collection< @NonEmpty String > strings = new ArrayList<>();
}
}
更多内容请关注微信公众号:全栈开发之技术栈
