[Java] reflection, enumeration, Lambda expression

insert image description here✨Blog homepage: Xinrong~
✨Series column: 【Java SE】
✨A short sentence: Persistence is difficult, persistence is expensive, and persistence is success!

1. Reflection

1. Overview of reflection

  • what is reflection

Java's reflection (reflection) mechanism is in the running state. For any class, you can know all the properties and methods of this class ; for any object, you can call any of its methods and properties. Now that you can get it, We can modify part of the type information; this function of dynamically obtaining information and dynamically calling object methods is called the reflection mechanism of the Java language.

  • Basic information about reflection

Many objects in a Java program will have two types at runtime: runtime type (RTTI) and compile-time type , for example, Person p = new Student(); in this code, p is of type Person at compile time and type of runtime is Student. Programs need real confidence in discovering objects and classes at runtime. By using the reflection program, it is possible to determine which classes the object and class belong to.

  • use of reflection
  1. In the daily third-party application development process, it is often encountered that a member variable, method or attribute of a certain class is private or only open to system applications . At this time, you can use Java's reflection mechanism to Get the desired private member or method.
  2. The most important use of reflection is to develop various general frameworks . For example, in spring, we hand over all class beans to spring container management, whether it is XML configuration beans or annotation configuration. When we obtain beans from the container for dependency injection, The container will read the configuration, and the information given in the configuration is the class information. According to this information, spring needs to create those beans, and spring will dynamically create these classes.

2. Use of reflection

2.1 Commonly used classes for reflection

class name use
class class An entity representing a class, representing classes and interfaces in a running Java application
Field class Represents the member variables of the class/attributes of the class
Method class method of the delegate class
Constructor class Delegate class constructor

Class represents the entity of the class, and represents the class and interface in the running Java application. After the Java file is compiled, the file is generated, and the JVM will .classload .classthe file at this time. The compiled Java file, that is, .classthe file will be compiled by the JVM resolves to an object, and this object is java.lang.Class. In this way, when the program is running, each java file eventually becomes an instance of the Class class. By applying Java's reflection mechanism to this instance, we can obtain or even add and change the attributes and actions of the class corresponding to the Class object , making this class a dynamic class.

2.2 Get the Class object through reflection

There are three ways to obtain objects through reflection:

  • Through the forName method in the Class class.
  • Obtained by class name.class.
  • Obtained by calling the getclass method with the instance object.

Below we demonstrate whether the objects obtained by using the three methods are the same object, and we will obtain the class information object of the relevant Student class.

Student class definition:

class Student{
    
    
    //私有属性name
    private String name = "rong";
    //公有属性age
    public int age = 18;
    //不带参数的构造方法
    public Student(){
    
    
        System.out.println("Student()");
    }
    //带两个参数的构造方法
    private Student(String name,int age) {
    
    
        this.name = name;
        this.age = age;
        System.out.println("Student(String,name)");
    }

    private void eat(){
    
    
        System.out.println("i am eating");
    }

    public void sleep(){
    
    
        System.out.println("i am sleeping");
    }

    private void function(String str) {
    
    
        System.out.println("私有方法function被调用:"+str);
    }

    @Override
    public String toString() {
    
    
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Get the Class object of the corresponding class:

public static void main(String[] args) {
    
    
    //有3种方式可以获取Class对象
    //1.通过对象的getClass()方法
    Student student1 = new Student();
    Class<?> c1 = student1.getClass();
    //2、通过类名.class获取
    Class<?> c2 = Student.class;
    //3. forName(“路径”)
    Class<?> c3 = null;
    try {
    
    
        c3 = Class.forName("Student");
    } catch (ClassNotFoundException e) {
    
    
        throw new RuntimeException(e);
    }
    System.out.println(c1.equals(c2));
    System.out.println(c1.equals(c3));
    System.out.println(c2.equals(c3));
}

Results of the:

Through the results, it is found that the objects obtained by the three methods are the same.

img

2.3 Obtain methods related to the Class class

method use
getClassLoader() get class loader
getDeclaredClasses() Returns an array containing objects of all classes and interface classes in this class (including private ones)
forName(String className) Returns an object of a class by class name
newInstance() Create an instance of the class
getName() Get the full path name of the class

2.4 Create an instance object using reflection

First obtain the Class object, and then create an instance object through the newInstance() method in the Class object.

It should be noted that the return value of the newInstance() method is a generic type, which will be erased as Object during the compilation phase, so we need to cast it when receiving it.

public static void main(String[] args) {
    
    
    //获取相关类的Class对象
    Class<?> c = Student.class;
    //使用newInstance方法创建实例
    try {
    
    
        //需要进行强转
        Student student = (Student) c.newInstance();
        System.out.println(student);
    } catch (InstantiationException e) {
    
    
        e.printStackTrace();
    } catch (IllegalAccessException e) {
    
    
        e.printStackTrace();
    }
}

Results of the:

An instance of the Student class is successfully created through reflection.

img

2.5 Use reflection to get the constructor in the instance object

method use
getConstructor(Class…<?> parameterTypes) Get the public constructor method matching the parameter type in this class
getConstructors() Get all public constructors of this class
getDeclaredConstructor(Class…<?> parameterTypes) Get the constructor method in this class that matches the parameter type
getDeclaredConstructors() Get all constructors of this class

Use reflection to get the constructor in the instance object and then create the instance object:

  1. Get the Class object.
  2. Get the constructor through the above method.
  3. setAccessibleIf you get a private constructor, you need to remember to enable access through the constructor method.
  4. Call the method in the constructor newInstanceto get the object.
public static void main(String[] args) throws ClassNotFoundException {
    
    
    //1.获取Clas对象
    Class<?> c = Class.forName("Student");
    //2.获取指定参数列表的构造器,演示获取Student中的一个私有构造器,参数传形参列表类型
    try {
    
    
        Constructor<?> constructor = c.getDeclaredConstructor(String.class, int.class);
        //获取的私有构造方法,需要打开访问权限,默认关闭
        constructor.setAccessible(true);
        //3.根据获取到的构造器获取实例对象,使用newInstance方法,需要传入构造器需要的参数
        Student student = (Student) constructor.newInstance("张三", 20);
        System.out.println(student);
    } catch (NoSuchMethodException e) {
    
    
        e.printStackTrace();
    } catch (InvocationTargetException e) {
    
    
        e.printStackTrace();
    } catch (InstantiationException e) {
    
    
        e.printStackTrace();
    } catch (IllegalAccessException e) {
    
    
        e.printStackTrace();
    }
}

operation result:

The private constructor is obtained, and the instance object is created according to the passed parameters.

img

2.6 Obtain the properties of the instance object through reflection

method use
getField(String name) Get a public attribute object
getFields() Get all public attribute objects
getDeclaredField(String name) get an attribute object
getDeclaredFields() get all property objects

Modify the private properties of an object by the following process:

  1. Get the Class object.
  2. Create or instantiate via reflection a class whose private fields need to be modified.
  3. Through the attribute name, call the above getDeclaredField method to obtain the corresponding attribute object.
  4. Set the permission to access private properties through the setAccessible method.
  5. Modify the corresponding attribute in the incoming object through the set method of the Field object.
public static void main(String[] args) {
    
    
    //1.获取Class对象
    Class<?> c = Student.class;
    try {
    
    
        //2.通过反射创建实例对象
        Student student = (Student) c.newInstance();
        //3.获取私有属性name
        Field field =  c.getDeclaredField("name");
        //4.给该私有属性开权限
        field.setAccessible(true);
        //5.修改该私有属性
        field.set(student, "被反射修改的私有属性");
        System.out.println(student);
    } catch (NoSuchFieldException e) {
    
    
        e.printStackTrace();
    } catch (InstantiationException e) {
    
    
        e.printStackTrace();
    } catch (IllegalAccessException e) {
    
    
        e.printStackTrace();
    }
}

operation result:

The private attribute name in the instance object has been modified.

img

2.7 Methods of obtaining instance objects through reflection

method use
getMethod(String name, Class…<?> parameterTypes) Get a public method of this class
getMethods() Get all public methods of this class
getDeclaredMethod(String name, Class…<?> parameterTypes) Get a method of this class
getDeclaredMethods() Get all methods of this class

Obtain the private method function in the Student object through the following process:

  1. Get the Class object of the related Student class.
  2. Create or instantiate a Student via reflection.
  3. The method object in the instance object is obtained through the class object, and the parameters are the method name and the list of formal parameter types.
  4. Grant access to the acquired private methods.
  5. Invoke methods through the invork method.
public static void main(String[] args) {
    
    
    try {
    
    
        //1.获取Class对象
        Class<?> c = Class.forName("Student");
        //2.获取Student的一个实例对象
        Student student = (Student) c.newInstance();
        //3.通过class对象获取实例的方法对象,参数为方法名,以及形参列表
        Method method =  c.getDeclaredMethod("function", String.class);
        //4.为私有方法开访问权限
        method.setAccessible(true);
        //5.通过invork方法调用方法
        method.invoke(student, "传入私有方法参数");
    } catch (ClassNotFoundException e) {
    
    
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
    
    
        e.printStackTrace();
    } catch (InstantiationException e) {
    
    
        e.printStackTrace();
    } catch (IllegalAccessException e) {
    
    
        e.printStackTrace();
    } catch (InvocationTargetException e) {
    
    
        e.printStackTrace();
    }
}

operation result:

Through reflection, the private method of the instance object can be obtained and called.

img

2.8 Obtain methods related to annotations in the class

method use
getAnnotation(Class annotationClass) Returns the public annotation object matching the parameter type in this class
getAnnotations() Return all public annotation objects of this class
getDeclaredAnnotation(Class annotationClass) Return all annotation objects in this class that match the parameter type
getDeclaredAnnotations() Return all annotation objects of this class

3. Advantages and disadvantages of reflection

Advantages :

  1. For any class, you can know all the properties and methods of this class; for any object, you can call any of its methods
  2. Increase program flexibility and scalability, reduce coupling, and improve self-adaptability
  3. Reflection has been used in many popular frameworks such as: Struts, Hibernate, Spring and so on.

Disadvantages :

  1. There are efficiency issues with using reflection. will lead to reduced program efficiency.
  2. Reflection technology bypasses the technology of the source code, thus creating maintenance problems. Reflective code is more complex than the corresponding direct code.

2. Enumeration

1. Overview of enumeration

Enumeration was introduced after JDK1.5; the keyword enum can create a limited set of named values ​​as a new type , and these named values ​​can be used as regular program components. This new type is enumeration .

主要用途是:将一组常量组织起来,在这之前表示一组常量通常使用定义常量的方式:

public static int final RED = 1;
public static int final GREEN = 2;
public static int final BLACK = 3;

但是常量举例有不好的地方,例如:可能碰巧有个数字1,但是他有可能误会为是RED,现在我们可以直接用枚举来进行组织,这样一来,就拥有了类型,枚举类型。而不是普通的整形1.

下面是创建一个Color枚举类型 :

public enum Color {
    
    
    RED,BLUE,GREEN,YELLOW,BLACK;
}

优点:将常量组织起来统一进行管理

场景:错误状态码,消息类型,颜色的划分,状态机等等…

本质是 java.lang.Enum 的子类,也就是说,自己写的枚举类,就算没有显示的继承 Enum ,但是其默认继承了这个类

2. 枚举的使用

2.1 switch语句中使用枚举

switch语句中可以使用枚举来提高代码的可读性。

其实enum关键字组织的是一个特殊的类,里面包含一个或多个的枚举对象,下面定义的Color,其实里面包含了3个枚举对象,每个对象都是Color类型。

enum Color {
    
    
    BLACK,YELLOW,GREEN;
}
public class Test {
    
    
    public static void main(String[] args) {
    
    
        Color color = Color.YELLOW;
        switch (color) {
    
    
            case BLACK:
                System.out.println("BLACK");
                break;
            case YELLOW:
                System.out.println("YELLOW");
                break;
            case GREEN:
                System.out.println("GREEN");
                break;
            default:
                break;
        }
    }
}

运行结果:

img

2.2 枚举enum中的常用方法

枚举中常用的方法如下:

方法名称 描述
values() 以数组形式返回枚举类型的所有成员
ordinal() 获取枚举成员的索引位置
valueOf() 将普通字符串转换为枚举实例
compareTo() 比较两个枚举成员在定义时的顺序

关于Enum类源码中找不到values()方法的解释:

values方法,在编译前无法找到,这是因为enum声明实际上定义了一个类,我们可以通过定义的enum调用一些方法,Java编译器会自动在enum类型中插入一些方法,其中就包括values(),valueOf(),所以我们的程序在没编译的时候,就没办法查看到values()方法以及源码,这也是枚举的特殊性。

  • 使用values()得到一个含有所有枚举对象的一个数组
public enum Color {
    
    
    BLACK,YELLOW,GREEN;

    public static void main(String[] args) {
    
    
        Color[] colors = Color.values();
        for (Color c : colors) {
    
    
            System.out.println(c);
        }
    }
}

运行结果:

img

  • 使用valueOf()通过一个字符串获取同名枚举:
public enum Color {
    
    
    BLACK,YELLOW,GREEN;
    public static void main(String[] args) {
    
    
        Color color = Color.valueOf("BLACK");
        System.out.println(color);
    }
}

运行结果:

img

  • 使用ordinal()获取枚举在枚举类中的位置次序,也就是索引:
public enum Color {
    
    
    BLACK,YELLOW,GREEN;
    public static void main(String[] args) {
    
    
        Color[] colors = Color.values();
        for (Color c : colors) {
    
    
            System.out.println(c + "的索引:" + c.ordinal());
        }
    }
}

运行结果:

img

  • 使用compareTo() 比较两个枚举成员在定义时的顺序:
public enum Color {
    
    
    BLACK,YELLOW,GREEN;
    public static void main(String[] args) {
    
    
        System.out.println(Color.GREEN.compareTo(Color.YELLOW));
        System.out.println(Color.BLACK.compareTo(Color.YELLOW));
    }
}

运行结果:

img

3. 自定义构造枚举对象

上面的例子中enum本质上其实是一个特殊的类,默认继承了抽象类java.lang.Enum,里面包含了一个或多个枚举对象,并且这些枚举对象默认情况下都是通过无参数的构造方法构造的,

其实我们可以在枚举类中自定义属性方法以及构造方法,实现自定义枚举对象.

看下面的写法, 和上面的例子是一样的 , 只不过上面的写法是无参构造省略了 ( )

img

我们可以自己在枚举类中定义一些属性, 然后去写含有含有参数的构造方法, 实现自定义枚举;

注意 : 枚举中的构造方法必须(默认)是私有的, 且当我们写了含有参数的构造方法时, 编译器不会再提提供无参的构造方法 , 所以此时需要按照我们自己写的构造方法传入参数;

public enum Color {
    
    
    BLACK("BLACK", 11, 1),
    YELLOW("YELLOW", 12, 2),
    GREEN("GREEN", 13, 3);
    public String colorName;
    public int colorId;
    public int ordonal;

    Color(String colorName, int colorId, int ordonal) {
    
    
        this.colorName = colorName;
        this.colorId = colorId;
        this.ordonal = ordonal;
    }

    @Override
    public String toString() {
    
    
        return "Color{" +
                "colorName='" + colorName + '\'' +
                ", colorId=" + colorId +
                ", ordonal=" + ordonal +
                '}';
    }

    public static void main(String[] args) {
    
    
        Color[] colors = Color.values();
        for (Color c : colors) {
    
    
            System.out.println(c);
        }
    }
}

运行结果:

img

4. 枚举的安全性

首先看下面的代码, 我们想要从外部通过反射获取到枚举类:

public class Test {
    
    
    public static void main(String[] args) {
    
    
        //尝试获取枚举对象
        Class<?> c = Color.class;
        try {
    
    
            //获取构造方法对象
            Constructor<?> constructor = c.getDeclaredConstructor(String.class, int.class, int.class);
            //开权限
            constructor.setAccessible(true);
            //通过构造方法构造对象
            Color color = (Color) constructor.newInstance("蓝色", 88, 2);
            System.out.println(color);
        } catch (NoSuchMethodException e) {
    
    
            e.printStackTrace();
        } catch (InvocationTargetException e) {
    
    
            e.printStackTrace();
        } catch (InstantiationException e) {
    
    
            e.printStackTrace();
        } catch (IllegalAccessException e) {
    
    
            e.printStackTrace();
        }
    }
}

运行结果:

img

结果中抛出一个java.lang.NoSuchMethodException: Color.<init>(java.lang.String, int, int)异常,表示没有找到我们给定参数列表的构造方法,但是我们枚举类中是定义过这个构造方法的,那么这里报错的原因是什么呢?

上面说过枚举类是默认继承抽象类java.lang.Enum的,所以要构造enum需要先帮助父类完成构造,但是枚举类与一般的类相比比较特殊,它不是使用super关键字进行显示地帮助父类构造,而是在编译后会多插入两个参数来帮助父类构造,也就是说,我们传参时要在原本所定义的构造方法参数列表基础上前面再添加String和int类型的两个参数

所以实际情况下,我们需要在反射获取构造器时,多写两个参数

Constructor<?> constructor = c.getDeclaredConstructor(String.class, int.class, String.class, int.class, int.class);

再次运行程序结果如下:

img

可以发现结果还是会抛出异常,但是此时抛的不是构造方法找不到的异常,而是枚举无法进行反射异常Exception in thread "main" java.lang.IllegalArgumentException: Cannot reflectively create enum objects;

所以枚举对象是无法通过反射得到的, 这也就保证了枚举的安全性;

其实枚举无法通过反射获取到枚举对象是因为在**newInstance****()**中获取枚举对象时,会过滤掉枚举类型,如果遇到的是枚举类型就会抛出异常。

img

5. 总结

  1. 枚举本身就是一个类,其构造方法默认为私有的,且都是默认继承与 java.lang.Enum
  2. 枚举可以避免反射和序列化问题
  3. 枚举实现单例模式是安全的

枚举的优点:

  • 枚举常量更简单安全
  • 枚举具有内置方法 ,代码更优雅

枚举的缺点:

  • 不可继承,无法扩展

三. Lambda表达式

1. 函数式接口

要了解Lambda表达式,首先需要了解什么是函数式接口,函数式接口定义:一个接口有且只有一个抽象方法 。

注意:

  1. 如果一个接口只有一个抽象方法,那么该接口就是一个函数式接口
  2. 如果我们在某个接口上声明了 @FunctionalInterface注解,那么编译器就会按照函数式接口的定义来要求该接 口,这样如果有两个抽象方法,程序编译就会报错的。所以,从某种意义上来说,只要你保证你的接口中只有一个抽象方法,你可以不加这个注解。加上就会自动进行检测的。

定义方式

@FunctionalInterface
interface NoParameterNoReturn {
    
    
	//注意:只能有一个方法
	void test();
}

基于jdk1.8, 还以有如下定义:

@FunctionalInterface
interface NoParameterNoReturn {
    
    
	void test();
	default void test2() {
    
    
		System.out.println("JDK1.8新特性,default默认方法可以有具体的实现");
	}
}

2. 什么是Lambda表达式?

Lambda表达式是Java SE 8中一个重要的新特性。lambda表达式允许你通过表达式来代替功能接口。 lambda表达 式就和方法一样,它提供了一个正常的参数列表和一个使用这些参数的主体(body,可以是一个表达式或一个代码 块)。 Lambda 表达式(Lambda expression),基于数学中的λ演算得名,也可称为闭包(Closure) 。

Lambda表达式的语法:

 (parameters) -> expression 或 (parameters) ->{
    
     statements; }

Lambda表达式由三部分组成

  1. paramaters:类似方法中的形参列表,这里的参数是函数式接口里的参数。这里的参数类型可以明确的声明也可不声明而由JVM隐含的推断。另外当只有一个推断类型时可以省略掉圆括号。
  2. ->:可理解为“被用于”的意思
  3. 方法体:可以是表达式也可以代码块,是函数式接口里方法的实现。代码块可返回一个值或者什么都不反回,这里的代码块块等同于方法的方法体。如果是表达式,也可以返回一个值或者什么都不反回。

常用的lambda表达式格式:

// 1. 不需要参数,返回值为 2
() -> 2
    
// 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)

3. Lambda表达式的基本使用

  1. 参数类型可以省略,如果需要省略,每个参数的类型都要省略。
  2. 参数的小括号里面只有一个参数,那么小括号可以省略
  3. 如果方法体当中只有一句代码,那么大括号可以省略
  4. 如果方法体中只有一条语句,其是return语句,那么大括号可以省略,且去掉return关键字

以下面这些接口为例:

//无返回值无参数
@FunctionalInterface
interface NoParameterNoReturn {
    
    
    void test();
}
//无返回值一个参数
@FunctionalInterface
interface OneParameterNoReturn {
    
    
    void test(int a);
}
//无返回值多个参数
@FunctionalInterface
interface MoreParameterNoReturn {
    
    
    void test(int a,int b);
}
//有返回值无参数
@FunctionalInterface
interface NoParameterReturn {
    
    
    int test();
}
//有返回值一个参数
@FunctionalInterface
interface OneParameterReturn {
    
    
    int test(int a);
}
//有返回值多参数
@FunctionalInterface
interface MoreParameterReturn {
    
    
    int test(int a,int b);
}

实现接口最原始的方式就是定义一个类去重写对应的方法,其次更简便的方式就是使用匿名内部类去实现接口;

public class TestDemo {
    
    
    public static void main(String[] args) {
    
    
        NoParameterNoReturn noParameterNoReturn = new NoParameterNoReturn(){
    
    
            @Override
            public void test() {
    
    
                System.out.println("hello");
            }
        };
        noParameterNoReturn.test();
    }
}

那么这里使用lambda表达式, 可以进一步进行简化;

public class TestDemo {
    
    
    public static void main(String[] args) {
    
    
        NoParameterNoReturn noParameterNoReturn = ()->{
    
    
            System.out.println("无参数无返回值");
        };
        noParameterNoReturn.test();
        
        OneParameterNoReturn oneParameterNoReturn = (int a)->{
    
    
            System.out.println("一个参数无返回值:"+ a);
        };
        oneParameterNoReturn.test(10);
        
        MoreParameterNoReturn moreParameterNoReturn = (int a,int b)->{
    
    
            System.out.println("多个参数无返回值:"+a+" "+b);
        };
        moreParameterNoReturn.test(20,30);
        
        NoParameterReturn noParameterReturn = ()->{
    
    
            System.out.println("有返回值无参数!");
            return 40;
        };
        //接收函数的返回值
        int ret = noParameterReturn.test();
        System.out.println(ret);
        
        OneParameterReturn oneParameterReturn = (int a)->{
    
    System.out.println("有返回值有一个参数!");
            return a;
        };
        ret = oneParameterReturn.test(50);
        System.out.println(ret);
        
        MoreParameterReturn moreParameterReturn = (int a,int b)->{
    
    
            System.out.println("有返回值多个参数!");
            return a+b;
        };
        ret = moreParameterReturn.test(60,70);
        System.out.println(ret);
    }
}

上面的的代码根据开头的省略规则还可以进一步省略, 如下:

public class TestDemo {
    
    
    public static void main(String[] args) {
    
    
        NoParameterNoReturn noParameterNoReturn
                = ()->System.out.println("无参数无返回值");
        noParameterNoReturn.test();

        OneParameterNoReturn oneParameterNoReturn
                = a-> System.out.println("一个参数无返回值:"+ a);
        oneParameterNoReturn.test(10);

        MoreParameterNoReturn moreParameterNoReturn
                = (a,b)-> System.out.println("多个参数无返回值:"+a+" "+b);
        moreParameterNoReturn.test(20,30);

        //有返回值无参数!
        NoParameterReturn noParameterReturn = ()->40;
        int ret = noParameterReturn.test();
        System.out.println(ret);

        //有返回值有一个参数!
        OneParameterReturn oneParameterReturn = a->a;
        ret = oneParameterReturn.test(50);
        System.out.println(ret);

        //有返回值多个参数!
        MoreParameterReturn moreParameterReturn = (a,b)->a+b;
        ret = moreParameterReturn.test(60,70);
        System.out.println(ret);
    }
}

还有一种写法更加简洁, 但可读性就… , 比如:

OneParameterNoReturn oneParameterNoReturn = a-> System.out.println(a);

可以简化成下面的样子, 看不太懂了…

OneParameterNoReturn oneParameterNoReturn = System.out::println;

4. 变量捕获

Lambda 表达式中存在变量捕获 ,了解了变量捕获之后,我们才能更好的理解Lambda 表达式的作用域 。

在匿名内部类中,只能捕获到常量,或者没有发生修改的变量,因为lambda本质也是实现函数式接口,所以lambda也满足此变量捕获的规则。

下面的代码捕获的变量num未修改, 程序可以正常编译和运行;

img

当捕获的变量num是修改过的, 则会报错;

img

5. Lambda在集合当中的使用

5.1 Collection接口中的forEach方法

注意:Collection的forEach()方 法是从接口 java.lang.Iterable 拿过来的。

The parameter that the forEach method needs to pass is Consumer<? super E> action. This parameter is also a functional interface, and the accept method in it needs to be rewritten.

img

Using an anonymous inner class, the t parameter in accept indicates the iterated element in the collection, we can set the operation on the element, and the rewritten method here only performs output operation;

public static void main(String[] args) {
    
    
    ArrayList<String> list = new ArrayList<>();
    list.add("欣");
    list.add("欣");
    list.add("向");
    list.add("荣");
    list.forEach(new Consumer<String>(){
    
    
        @Override
        public void accept(String str){
    
    
            //简单遍历集合中的元素。
            System.out.print(str+" ");
        }
    });
}

Results of the:

img

We can use lambda to express the above anonymous inner class, which has only one parameter and no return value, and the above code becomes

public static void main(String[] args) {
    
    
    ArrayList<String> list = new ArrayList<>();
    list.add("欣");
    list.add("欣");
    list.add("向");
    list.add("荣");
    list.forEach(s -> System.out.print(s + " "));
}

5.2 forEach method in Map

The forEach method in the map is actually similar to the forEach method in the previous Collection. It just changes a parameter. This parameter BiConsumer<? super K, ? super V> action is also a functional interface, and we need to pass in an implementation The implementation class of this interface.

img

Use an anonymous inner class:

public static void main(String[] args) {
    
    
    Map<Integer, String> map = new HashMap<>();
    map.put(1, "欣");
    map.put(2, "欣");
    map.put(3, "向");
    map.put(4, "荣");
    map.forEach(new BiConsumer<Integer, String>(){
    
    
        @Override
        public void accept(Integer k, String v){
    
    
            System.out.println(k + "=" + v);
        }
    });
}

operation result:

img

The above code can also be implemented using a lambda expression, which is a functional interface with two parameters and no return value. The above code is changed to:

public static void main(String[] args) {
    
    
    Map<Integer, String> map = new HashMap<>();
    map.put(1, "欣");
    map.put(2, "欣");
    map.put(3, "向");
    map.put(4, "荣");
    map.forEach((k,v)-> System.out.println(k + "=" + v));
}

5.3 The sort method in most interfaces

The sort method in most interfaces is sorted in ascending order by default. If you need to sort custom classes or implement custom rule sorting, you need to pass in an additional Comparator implementation class object (comparator); here Take the sort method in the List collection as an example.

img

public static void main(String[] args) {
    
    
    ArrayList<String> list = new ArrayList<>();
    list.add("aaaa");
    list.add("bbb");
    list.add("cc");
    list.add("d");
    list.sort(new Comparator<String>() {
    
    
        @Override
        public int compare(String str1, String str2){
    
    
            //注意这里比较的是长度
            return str1.length()-str2.length();
        }
    });
    System.out.println(list);
}

operation result:

img

The above code can also be implemented using a lambda expression, which is a functional interface with two parameters and a return value. The above code is changed to:

 public static void main(String[] args) {
    
    
    ArrayList<String> list = new ArrayList<>();
    list.add("aaaa");
    list.add("bbb");
    list.add("cc");
    list.add("d");
    //调用带有2个参数的方法,且返回长度的差值
    list.sort((str1,str2)-> str1.length()-str2.length());
    System.out.println(list);
}

6. Summary

The advantages of Lambda expressions are obvious. At the code level, the code becomes very concise. The disadvantage is also obvious, the code is not easy to read.

  • Advantages :
  1. Simple code and fast development
  2. Convenient functional programming
  3. Very easy to do parallel computing
  4. Java introduces Lambda to improve collection operations
  • Disadvantages :
  1. poor code readability
  2. In non-parallel computing, many calculations may not have higher performance than traditional for
  3. not easy to debug

Guess you like

Origin blog.csdn.net/Trong_/article/details/127639053