Jdk8新特性


前言

jdk8新特性涉及的主要内容
1.Lambda表达式
2.函数式接口
3.方法引用与构造器引用
4.StreamAPI
5.接口中的默认方法与静态方法
6.新时间日期API
7.其他新特性

jdk8新特性
速度更快
代码更少(增加了新的语法Lambda表达式)
强大的StreamAPI
便于并行
最大化减少空指针异常Optional


一、Lambda表达式

1.Lambda表达式

Lambda是一个匿名函数,我们可以把Lambda表达式理解为是一段可以传递的代码(将代码像数据一样进行传递)。可以写出更简洁、更灵活的代码。作为一种更紧凑的代码风格,使Java的语言表达能力得到了提升。

Lambda表达式演变过程:
匿名内部类 --> Lambda表达式

Lambda 表达式在Java 语言中引入了一个新的语法元素和操作符。这个操作符为 “->” , 该操作符被称为Lambda 操作符箭头操作符。它将Lambda 分为两个部分:
左侧:指定了 Lambda 表达式需要的所有参数
右侧:指定了 Lambda 体,即 Lambda 表达式要执行的功能。

2.Lambda表达式语法

语法格式一:语法格式一:无参,无返回值

int num=0;
//匿名内部类常数项
Runnable runnable=new Runnable() {
	@Override
	public void run() {
   		System.out.println("num = " + num);
	}
};
runnable.run();
        
//Lambda表达式
Runnable runnable1=()->System.out.println("num = " + num);
runnable1.run();

语法格式二:有一个参数,并且无返回值
Lambda 只需要一个参数时,参数的小括号可以省略

Consumer<String> consumer=new Consumer<String>() {
	@Override
	public void accept(String s) {
     	System.out.println("s = " + s);
    }
};
consumer.accept("Lambda表达式语法格式二");

Consumer<String> consumer1=(s)-> System.out.println("s = " + s);
consumer1.accept("Lambda表达式语法格式二"); 

//一个参数时,省略括号
Consumer<String> consumer2=s-> System.out.println("s = " + s);
consumer2.accept("一个参数时,省略括号");     

语法格式三:Lambda 需要两个参数,并且有返回值
当Lambda 体只有一条语句时,return 与大括号可以省略
Lambda 表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出,数据类型,即“类型推断”

Comparator<Integer> comparator=new Comparator<Integer>() {
	@Override
	public int compare(Integer o1, Integer o2) {
    		System.out.println("Lambda表达式语法格式二");
    		return o1.compareTo(o2);
	}
};

Comparator<Integer> comparator1=(o1,o2)->{
	System.out.println("Lambda表达式语法格式二");
	return o1.compareTo(o2);
};

Comparator<Integer> comparator2=(o1,o2)->o1.compareTo(o2);

Comparator<Integer> comparator3=(Integer o1,Integer o2)->Integer.compare(o1,o2);

二、函数式接口

1.函数式接口

⚫ 只包含一个抽象方法的接口,称为函数式接口。
⚫ 可以通过 Lambda 表达式来创建该接口的对象。(若 Lambda 表达式抛出一个受检异常,那么该异常需要在目标接口的抽象方法上进行声明)。
⚫ 我们可以在任意函数式接口上使用 @FunctionalInterface注解,这样做可以检查它是否是一个函数式接口,同时 javadoc 也会包含一条声明,说明这个接口是一个函数式接口。

/**
 * 自定义函数式接口
 */
@FunctionalInterface
public interface MyFunction {
    public double getDouble(Double args);
}
/**
 * 函数式接口中使用泛型
 */
@FunctionalInterface
public interface MyFunction2<T,R> {
    public R getValue(T t1,T t2);
}

作为参数传递 Lambda 表达式:为了将 Lambda 表达式作为参数传递,接
收Lambda 表达式的参数类型必须是与该 Lambda 表达式兼容的函数式接口
的类型。即作为参数传递的Lambda表达式的参数类型和Lambda表达式执行结果必须与该Lambda表达式兼容的函数式接口对应。

@Test
public void test5(){
      String result = this.toUpperCase("dfafdasfdasf", str -> str.toUpperCase());
      System.out.println("result = " + result);
}
private String toUpperCase(String str,MyFunction myFunction){
     return myFunction.getValue(str);
}

2.Java 内置四大核心函数式接口

在这里插入图片描述

1.消费型接口

用途:对类型为T的对象应用操作
方法:void accept(T t)

	/**
     * 消费型接口
     */
    @Test
    public void test1(){
        Consumer<List<Employee>> consumer=(employees)->{
          employees.add(new Employee(1,"张三",63,666.3));
          employees.add(new Employee(2,"李四",45,654.3));
          employees.add(new Employee(3,"王五",36,785.6));
        };
        List<Employee> employees= Lists.newArrayList();
        this.optionList(employees,consumer);
    }

    public void optionList(List<Employee> employees,Consumer<List<Employee>> consumer){
         consumer.accept(employees);
    }

2.供给型接口

用途:返回类型为T的对象
包含方法:T get()

	/**
     * 供给型接口
     */
    @Test
    public void test2(){
        Supplier<Employee> supplier=()->{
            Employee employee=new Employee();
            employee.setId(Integer.parseInt(String.valueOf(System.currentTimeMillis()).substring(10,13)));
            employee.setAge(Math.getExponent((Math.random()+1)*10));
            employee.setName("张三");
            employee.setSalary(Math.ceil((Math.random()+1000)*1000)/100);
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return employee;
        };
        List<Employee> employees=Lists.newArrayList();

        this.getEmployee(employees,supplier).forEach(System.out::println);
    }

    private List<Employee> getEmployee(List<Employee> employees,Supplier<Employee> supplier){
        for (int i = 0; i < 20; i++) {
            employees.add(supplier.get());
        }
        return employees;
    }

3.函数式接口

用途:对类型为T的对象应用操作,并返回结果。结果是R类型的对象。
方法:R apply(T t);

	/**
     * 函数型接口
     */
    @Test
    public void test3(){
        Function<List<Employee>, Map<String,String>> function=(e)->{
            Map<String,String> map= Maps.newHashMap();
            for (Employee employee : e) {
                map.put(employee.getName(),String.valueOf(employee.getSalary()));
            }
            return map;
        };
        List<Employee> ems= Arrays.asList(new Employee(101, "张三", 18, 9999.99),
                new Employee(102, "李四", 59, 6666.66),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "赵六", 8, 6666.66),
                new Employee(104, "赵七", 8, 3333.33),
                new Employee(104, "赵八", 8, 5555.55),
                new Employee(104, "赵九", 8, 7777.77),
                new Employee(105, "田七", 38, 6555.55),
                new Employee(105, "田七", 54, 8555.55)
        );
        Map<String, String> employeeMap = this.getEmployeeMap(ems, function);

    }

    private Map<String,String> getEmployeeMap(List<Employee> employees,Function<List<Employee>,Map<String,String>> function){
        return function.apply(employees);
    }

4.断定型接口

用途:确定类型为T的对象是否满足某约束,并返回boolean 值。
方法:boolean test(T t);

 	/**
     * 断定接口
     */
    @Test
    public void test4(){
        Predicate<Employee> predicate=(e)->{
         return e.getSalary()>5000&&e.getName().substring(0,1).equals("田");
        };
        List<Employee> ems= Arrays.asList(new Employee(101, "张三", 18, 9999.99),
                new Employee(102, "李四", 59, 6666.66),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "赵六", 8, 6666.66),
                new Employee(104, "赵七", 8, 3333.33),
                new Employee(104, "赵八", 8, 5555.55),
                new Employee(104, "赵九", 8, 7777.77),
                new Employee(105, "田七", 38, 6555.55),
                new Employee(105, "田七", 28, 5555.55),
                new Employee(105, "田七", 18, 4555.55),
                new Employee(105, "田七", 34, 7555.55),
                new Employee(105, "田七", 54, 8555.55)
        );
        this.filterList(ems,predicate).forEach(System.out::println);

    }

    private List<Employee> filterList(List<Employee> employees,Predicate<Employee> predicate){
        List<Employee> employees1=Lists.newArrayList();
        if (!Objects.isNull(employees)&&!employees.isEmpty()) {
            for (Employee employee : employees) {
                if (predicate.test(employee)) {
                    employees1.add(employee);
                }
            }
        }
        return employees1;
    }

5.其它函数式接口

在这里插入图片描述

3.方法引用与构造器引用

1.方法引用

当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用!
实现抽象方法的参数列表,必须与方法引用方法的参数列表保持一致!
方法引用:使用操作符 “::” 将方法名和对象或类的名字分隔开来。
如下三种主要使用情况:
⚫ 对象::实例方法
⚫ 类::静态方法
⚫ 类::实例方法

注意:
①方法引用所引用的方法的参数列表与返回值类型,需要与函数式接口中抽象方法的参数列表和返回值类型保持一致!
②若Lambda 的参数列表的第一个参数,是实例方法的调用者,第二个参数(或无参)是实例方法的参数时,格式: ClassName::MethodName

	/**
     * 对象名::实例方法名
     */
    @Test
    public void test1(){
        Employee employee=new Employee(1,"张三",15,5555.55);
        Supplier<String> supplier=employee::getName;
        System.out.println(supplier.get());
    }


    /**
     * 类名::静态方法名
     */
    @Test
    public void test2(){
        Comparator<Integer> comparator=(x,y)->Integer.compare(x,y);
        System.out.println(comparator.compare(1, 2));

        Comparator<Integer> comparator1=Integer::compare;
        System.out.println(comparator1.compare(1, 2));

    }

    /**
     * 类名::实例方法名
     */
    @Test
    public void test3(){
        BiFunction<String,String,Boolean> biFunction=(x,y)->x.equals(y);
        System.out.println(biFunction.apply("方法引用", "方法引用"));

        BiFunction<String,String,Boolean> biFunction1=String::equals;
        System.out.println(biFunction1.apply("方法引用", "方法引用"));

    }

2.构造器引用

格式: ClassName::new
与函数式接口相结合,自动与函数式接口中方法兼容。
注意:
构造器的参数列表,需要与函数式接口中参数列表保持一致!

	   Employee employee=new Employee(1);
       Function<Integer,Employee> function=Employee::new;
       Employee employee1 = function.apply(1);

       Employee employee2=new Employee("张三",15);
       BiFunction<String,Integer,Employee> function1=Employee::new;
       Employee employee3 = function1.apply("张三", 34);

3.数组引用

格式: type[] :: new

/**
     * 数组引用
     */
    @Test
    public void test5(){
       String[] str=new String[8];
       Function<Integer,String[]> biFunction1=(x)->new String[x];
       Function<Integer,String[]> biFunction=String[]::new;
    }

4.Stream API

Stream 是 Java8 中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。使用Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数据库查询。也可以使用 Stream API 来并行执行操作。简而言之,Stream API 提供了一种高效且易于使用的处理数据的方式。

流(Stream) 到底是什么呢?
数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。
集合讲的是数据,流讲的是计算!
注意:
①Stream 自己不会存储元素。
②Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。
③Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。

Stream 的操作三个步骤
⚫ 创建 Stream
一个数据源(如:集合、数组),获取一个流
⚫ 中间操作
一个中间操作链,对数据源的数据进行处理
⚫ 终止操作(终端操作)
一个终止操作,执行中间操作链,并产生结果
在这里插入图片描述

1.创建Stream流

1.java8中通过Collection接口创建

⚫ default Stream stream() : 返回一个顺序流
⚫ default Stream parallelStream() : 返回一个并行流

2.由数组创建流

Java8 中的 Arrays 的静态方法 stream() 可以获取数组流:
⚫ static Stream stream(T[] array): 返回一个流重载形式,能够处理对应基本类型的数组:
⚫ public static IntStream stream(int[] array)
⚫ public static LongStream stream(long[] array)
⚫ public static DoubleStream stream(double[] array)

3.由值创建流

可以使用静态方法 Stream.of(), 通过显示值创建一个流。它可以接收任意数量的参数。
⚫ public static Stream of(T… values) : 返回一个流

4.由函数创建流:创建无限流

可以使用静态方法 Stream.iterate() 和Stream.generate(), 创建无限流。
⚫ 迭代
public static Stream iterate(final T seed, finalUnaryOperator f)
⚫ 生成
public static Stream generate(Supplier s)

		/**
         * 1.创建Stream
         *  Collection提供了两个方法 stream()与 parallelStream()
         */
        List<String> list= Lists.newArrayList();
        //创建一个顺序流
        Stream<String> stream = list.stream();
        //创建一个并行流
        Stream<String> parallelStream = list.parallelStream();

        //2.通过Arrays的静态方法stream()创建
        String[] strings = list.toArray(new String[]{});
        Stream<String> stream1 = Arrays.stream(strings);

        //3.通过 Stream 类中的静态方法 of()
        Stream<String> stream2 = Stream.of("张三", "李四", "王五", "刘六", "王维");
        Stream<Employee> stream3 = Stream.of(new Employee(1, "张三", 14, 8976.34));

        //4.使用静态方法Stream.iterate()和Stream.generate()创建无限流
        Stream<Integer> iterate = Stream.iterate(0, x -> x+2).limit(10);
        iterate.forEach(System.out::println);
        Stream<Double> generate = Stream.generate(() -> Math.random()).limit(10);
        generate.forEach(System.out::println);

2.Stream的中间操作

多个中间操作可以连接起来形成一个流水线,除非流水线上触发终止操作,否则中间操作不会执行任何的处理!而在终止操作时一次性全部处理,称为“惰性求值”。

1.筛选与切片

在这里插入图片描述

 List<Employee> employees=Lists.newArrayList(new Employee(101, "张三", 18, 9999.99),
                new Employee(102, "李四", 59, 6666.66),
                new Employee(103, "王五", 38, 3333.33),
                new Employee(103, "王五", 38, 3333.33),
                new Employee(104, "赵六", 81, 9999.66),
                new Employee(104, "赵七", 18, 3333.33),
                new Employee(104, "赵八", 48, 5555.55),
                new Employee(104, "赵九", 58, 7777.77),
                new Employee(105, "田七", 38, 5555.55));

        //筛选与切片
        Stream<Employee> employeeStream = employees.stream().filter(employee -> {
            return employee.getAge() > 48 && employee.getSalary() > 5000;
        });
        employees.stream().filter(employee -> employee.getSalary()>5000).skip(2);
        employees.stream().filter(employee -> employee.getSalary()>5000).limit(2);
        employees.stream().distinct();
2.映射

在这里插入图片描述

 List<Employee> employees=Lists.newArrayList(new Employee(101, "张三", 18, 9999.99),
            new Employee(102, "李四", 59, 6666.66),
            new Employee(103, "王五", 38, 3333.33),
            new Employee(103, "王五", 38, 3333.33),
            new Employee(104, "赵六", 81, 9999.66),
            new Employee(104, "赵七", 18, 3333.33),
            new Employee(104, "赵八", 48, 5555.55),
            new Employee(104, "赵九", 58, 7777.77),
            new Employee(105, "田七", 38, 5555.55));

    @Test
    public void test(){
        //映射
        Integer[] num=new Integer[]{2,3,4,5,6,7};
        //把num数组中每个元素做平方运算,产生一个新的数组
        List<Integer> collect = Arrays.stream(num).map(x -> x * x).collect(Collectors.toList());
        Integer[] integers = collect.toArray(new Integer[]{});
        //如何根据map()和reduce()函数获取集合长度
        Stream<Integer> integerStream = employees.stream().map(e -> 1);
        //integerStream.forEach(System.out::println);
        Optional<Integer> reduce = integerStream
                .reduce(Integer::sum);
        System.out.println(reduce.get());

        employees.stream().mapToDouble((e)->e.getSalary()).forEach(System.out::println);

    }


    @Test
    public void test1(){

        List<String> strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");

        Stream<String> stream = strList.stream()
                .map(String::toUpperCase);

        stream.forEach(System.out::println);

        Stream<Stream<Character>> stream2 = strList.stream()
                .map(TestStreamAPI::filterCharacter);

        stream2.forEach((sm) -> {
            sm.forEach(System.out::println);
        });

        System.out.println("---------------------------------------------");

        Stream<Character> stream3 = strList.stream()
                .flatMap(TestStreamAPI::filterCharacter);

        stream3.forEach(System.out::println);
    }

    public static Stream<Character> filterCharacter(String str){
        List<Character> list = new ArrayList<>();

        for (Character ch : str.toCharArray()) {
            list.add(ch);
        }

        return list.stream();
    }
3.排序

在这里插入图片描述

 /**
     * sorted() 自然排序
     * sorted(Comparator<? super T> comparator)——定制排序
     */

    @Test
    public void Test2(){
        employees.stream().map(Employee::getName).sorted().forEach(System.out::println);
        System.out.println("----------------");
        employees.stream().map(Employee::getSalary).sorted().forEach(System.out::println);

        //定制排序
        employees.stream().sorted((e1,e2)->{
            if (e1.getAge()==e2.getAge()){
                return e1.getName().compareTo(e2.getName());
            }else{
                return Integer.compare(e1.getAge(),e2.getAge());
            }
        }).forEach(System.out::println);
    }

3.Stream的终止操作

终端操作会从流的流水线生成结果。其结果可以是任何不是流的值,例如:List、Integer,甚至是 void

1.查找与匹配

在这里插入图片描述
在这里插入图片描述

	 /**
     * 终止操作
     * allMatch-检查是否匹配所有元素
     * anyMatch-检查是否至少匹配一个元素
     * noneMathc-检查是否没有元素匹配
     * findFirst-返回第一个元素
     * findAny-返回流中任意一个元素
     * count-返回流中元素个数
     * max-返回流中的最大值
     * min-返回流中的最小值
     */
    @Test
    public void Test3(){
        //判断每一个员工的工资是否大于5000

        boolean b = employees.stream().allMatch(e -> e.getSalary() > 3000);
        
        boolean b1 = employees.stream().anyMatch(e -> e.getName().substring(0, 1).equals("赵"));
        
        boolean b2 = employees.stream().noneMatch(e -> e.getAge() < 10);
        
        Optional<Employee> first = employees.stream().findFirst();
        
        Optional<Employee> any = employees.stream().findAny();
        
        long count = employees.stream().count();
        
        Optional<Employee> max = employees.stream().max((e1, e2) -> {
            return Double.compare(e1.getSalary(), e2.getSalary());
        });
    }
2.归约

在这里插入图片描述

	/**
     * reduce(T identity, BinaryOperator) / reduce(BinaryOperator) ——可以将流中元素反复结合起来,得到一个值。
     */
    @Test
    public void Test4(){
        List<Integer> list=Arrays.asList(1,2,3,4,5,6,7,8,9,10);
        Integer reduce = list.stream().reduce(20, (x, y) -> x + y);

        //计算所有员工的工资和
        Optional<Double> reduce1 = employees.stream().map(Employee::getSalary).reduce((x, y) -> x + y);

        //统计所有员工的名字含有“六”字的个数
        Integer count = employees.stream().map(Employee::getName)
                .flatMap(TestStreamAPI::filterCharacter)//将员工所有名字转换为字符流
                .map(x -> {
                    if (x.equals('六')) {
                        return 1;
                    } else {
                        return 0;
                    }
                })
                .reduce(Integer::sum).get();
    }
3.收集

在这里插入图片描述

Collector 接口中方法的实现决定了如何对流执行收集操作(如收集到 List、Set、Map)。但是 Collectors 实用类提供了很多静态方法,可以方便地创建常见收集器实例,具体方法与实例如下表:
在这里插入图片描述
在这里插入图片描述

	/**
     *  collect——将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法
     */
    @Test
    public void test5(){
        //把元素收集到list
        List<Double> salarys = employees.stream().map(Employee::getSalary).collect(Collectors.toList());
        //把元素收集到set
        Set<String> nameSet = employees.stream().map(Employee::getName).collect(Collectors.toSet());
        //把元素收集到新创建的集合
        ArrayList<Employee> employees1 = employees.stream().collect(Collectors.toCollection(ArrayList::new));
        //计算流中元素的个数
        Long collect = employees.stream().collect(Collectors.counting());
        /**
         * 对流中元素属性求和
         * 1.计算double型属性
         * Collectors.summarizingDouble()------>DoubleSummaryStatistics{count=9, sum=55555.170000, min=3333.330000, average=6172.796667, max=9999.990000}
         * Collectors.summingDouble()-------->aDouble = 55555.17
         * 2.计算int型属性
         * Collectors.summarizingInt()
         * Collectors.summingInt()
         * 3.计算long型属性
         * Collectors.summarizingLong()
         * Collectors.summingLong()
         */
        DoubleSummaryStatistics summaryStatistics = employees.stream().collect(Collectors.summarizingDouble(Employee::getSalary));
        Double aDouble = employees.stream().collect(Collectors.summingDouble(Employee::getSalary));
        /**
         * 对流中元素属性求平均值
         * 1.计算double型属性
         * Collectors.averagingDouble()
         * 2.计算int型属性
         * Collectors.averagingInt()
         * 3.计算long型属性
         * Collectors.averagingLong()
         */
        Double aDouble1 = employees.stream().collect(Collectors.averagingDouble(Employee::getSalary));

        //连接流中的字符串
        String collect1 = employees.stream().map(Employee::getName).collect(Collectors.joining());
        //根据比较器选择最大值
        Optional<Employee> collect2 = employees.stream().collect(Collectors.maxBy(Comparator.comparing(Employee::getSalary)));
        Optional<Double> collect3 = employees.stream().map(Employee::getSalary).collect(Collectors.maxBy(Double::compareTo));
        //根据比较器选择最小值
        Optional<Employee> collect4 = employees.stream().collect(Collectors.minBy(Comparator.comparing(Employee::getName)));
        Optional<String> collect5 = employees.stream().map(Employee::getName).collect(Collectors.minBy(String::compareTo));
        //从一个作为累加器的初始值开始,利用BinaryOperator与流中元素逐个结合,从而归约成单个值
        Integer collect6 = employees.stream().collect(Collectors.reducing(0, Employee::getAge, Integer::sum));
        //包裹另一个收集器,对其结果转换函数
        Object[] collect7 = employees.stream().collect(Collectors.collectingAndThen(Collectors.toList(), (e) -> e.toArray()));
        //根据某属性值对流分组,属性为K,结果为V
        Map<String, List<Employee>> collect8 = employees.stream().collect(Collectors.groupingBy(Employee::getName));
        //根据true或false进行分区
        Map<Boolean, List<Employee>> collect9 = employees.stream().collect(Collectors.partitioningBy((e) -> e.getAge() > 35));

4.并行流与串行流

并行流:就是把一个内容分成多个数据块,并用不同的线程分别处理每个数据块的流。
Java 8 中将并行进行了优化,我们可以很容易的对数据进行并行操作。Stream API 可以声明性地通过parallel()sequential() 在并行流与顺序流之间进行切换。

	/**
     *  并行流/串行流
     */
    @Test
    public void test6(){

        long start = System.currentTimeMillis();
        //并行流
        Map<String, Double> map = employees.stream().parallel().collect(Collectors.toMap(Employee::getName, Employee::getSalary, (k1, k2) -> k2));
        for (Map.Entry<String, Double> entry : map.entrySet()) {
            System.out.println(entry.getKey()+":"+entry.getValue());
        }
        long end = System.currentTimeMillis();
        System.out.println(end-start);
        long start1 = System.currentTimeMillis();
        //串行流
        Map<String, Double> map1 = employees.stream().sequential().collect(Collectors.toMap(Employee::getName, Employee::getSalary, (k1, k2) -> k2));
        for (Map.Entry<String, Double> entry : map1.entrySet()) {
            System.out.println(entry.getKey()+":"+entry.getValue());
        }
        long end1 = System.currentTimeMillis();
        System.out.println(end1-start1);

    }

5.了解 Fork/Join 框架

Fork/Join 框架:就是在必要的情况下,将一个大任务,进行拆分(fork)成若干个小任务(拆到不可再拆时),再将一个个的小任务运算的结果进行 join 汇总.

在这里插入图片描述

Fork/Join 框架与传统线程池的区别
采用 “工作窃取”模式(work-stealing):
当执行新的任务时它可以将其拆分分成更小的任务执行,并将小任务加到线程队列中,然后再从一个随机线程的队列中偷一个并把它放在自己的队中。
相对于一般的线程池实现,fork/join框架的优势体现在对其中包含的任务的处理方式上.在一般的线程池中,如果一个线程正在执行的任务由于某些原因无法继续运行,那么该线程会处于等待状态.而在fork/join框架实现中,如果某个子问题由于等待另外一个子问题的完成而无法继续运行.那么处理该子问题的线程会主动寻找其他尚未运行的子问题来执行.这种方式减少了线程的等待时间,提高了性能.

public class ForkJoinCalculate extends RecursiveTask<Long> {

    private long start;
    private long end;

    public ForkJoinCalculate(long start, long end) {
        this.start = start;
        this.end = end;
    }

    //临界值
    private static final long THRESHOLD=10000L;

    @Override
    protected Long compute() {
        long length = end - start;
        if (length<=THRESHOLD) {
            long sum=0;
            for (long i = start; i <= end; i++) {
                sum+=i;
            }
            return sum;
        }else{
            long middle = (end + start) / 2;
            ForkJoinCalculate left=new ForkJoinCalculate(start,middle);
            left.fork();//拆分,并将子任务压入线程队列

            ForkJoinCalculate right=new ForkJoinCalculate(middle+1,end);
            right.fork();
            return left.join()+right.join();
        }
    }
}

public class TestForkJoin {

    @Test
    public void test1(){
        long start = System.currentTimeMillis();
        ForkJoinPool forkJoinPool=new ForkJoinPool();
        ForkJoinTask<Long> task=new ForkJoinCalculate(0L,100000000L);
        long sum = forkJoinPool.invoke(task);
        System.out.println(sum);
        long end = System.currentTimeMillis();
        System.out.println(end-start);
    }

    @Test
    public void test2(){
        long start = System.currentTimeMillis();

        long sum = 0L;

        for (long i = 0L; i <= 100000000L; i++) {
            sum += i;
        }

        System.out.println(sum);

        long end = System.currentTimeMillis();

        System.out.println("耗费的时间为: " + (end - start)); //34-3174-3132-4227-4223-31583
    }

    @Test
    public void test3(){
        long start = System.currentTimeMillis();

        Long sum = LongStream.rangeClosed(0L, 100000000000L)
                .parallel()
                .sum();

        System.out.println(sum);

        long end = System.currentTimeMillis();

        System.out.println("耗费的时间为: " + (end - start)); //2061-2053-2086-18926
    }
}

5.新时间日期API

1.使用LocalDate、LocalTime、LocalDateTime

LocalDate、LocalTime、LocalDateTime 类的实例是不可变的对象,分别表示使用 ISO-8601日历系统的日期、时间、日期和时间。它们提供了简单的日期或时间,并不包含当前的时间信息。也不包含与时区相关的信息。

在这里插入图片描述

@Test
    public void test1(){
        //now() 静态方法,根据当前时间创建对象
        LocalDate localDate = LocalDate.now();
        LocalTime localTime = LocalTime.now();
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println("localDate = " + localDate);
        System.out.println("localTime = " + localTime);
        System.out.println("localDateTime = " + localDateTime);

        System.out.println("-------------------------------");

        //of() 静态方法,根据指定日期/时间创建对象
        LocalDate of = LocalDate.of(2022, 1, 21);
        LocalDateTime of1 = LocalDateTime.of(2022, 2, 22, 13, 59, 34);
        LocalDateTime of3 = LocalDateTime.of(2022, Month.of(1), 22, 13, 59, 34);
        LocalTime of2 = LocalTime.of(1, 34, 0);
        System.out.println("of = " + of);
        System.out.println("of1 = " + of1);
        System.out.println("of2 = " + of2);
        System.out.println("of3 = " + of3);

        System.out.println("--------------------------------");

        //plusDays, plusWeeks,plusMonths, plusYears,plusHours,plusMinutes,plusSeconds,plusNanos
        // 向当前 LocalDate,LocalDateTime,LocalTime 对象添加几天、几周、几个月、几年,几小时,几分,几秒,几纳秒
        LocalDateTime localDateTime1 = of1.plusDays(1);
        System.out.println("localDateTime1 = " + localDateTime1);
        LocalDateTime localDateTime2 = of1.plusMonths(2);
        System.out.println("localDateTime2 = " + localDateTime2);
        LocalDateTime localDateTime3 = of1.plusYears(3);
        System.out.println("localDateTime3 = " + localDateTime3);
        LocalDateTime localDateTime5 = localDateTime.plusWeeks(3);
        System.out.println("localDateTime5 = " + localDateTime5);
        LocalDateTime localDateTime4 = of1.plusYears(1).plusMonths(2).plusDays(3);
        System.out.println("localDateTime4 = " + localDateTime4);

        System.out.println("------------------------------");
        //minusDays, minusWeeks,minusMonths, minusYears,minusHours,minusMinutes,minusSeconds,minusNanos
        //从当前 LocalDate,LocalDateTime,LocalTime 对象减去几天、几周、几个月、几年,几小时,几分,几秒,几纳秒
        LocalDateTime localDateTime6 = of1.minusYears(1);
        LocalDateTime localDateTime7 = of1.minusMonths(2);
        LocalDateTime localDateTime8 = of1.minusWeeks(2);
        LocalDateTime localDateTime9 = of1.minusDays(22);
        LocalDateTime localDateTime10 = of1.minusHours(14);
        LocalDateTime localDateTime11 = of1.minusMinutes(60);
        LocalDateTime localDateTime12 = of1.minusSeconds(35);
        LocalDateTime localDateTime13 = of1.minusNanos(32);
        System.out.println("of1 = " + formatDate(of1));
        System.out.println("localDateTime6 = " + formatDate(localDateTime6));
        System.out.println("localDateTime7 = " + formatDate(localDateTime7));
        System.out.println("localDateTime8 = " + formatDate(localDateTime8));
        System.out.println("localDateTime9 = " + formatDate(localDateTime9));
        System.out.println("localDateTime10 = " + formatDate(localDateTime10));
        System.out.println("localDateTime11 = " + formatDate(localDateTime11));
        System.out.println("localDateTime12 = " + formatDate(localDateTime12));
        System.out.println("localDateTime13 = " + formatDate(localDateTime13));

        System.out.println("-----------------------------");
        //plus, minus 添加或减少一个Duration 或 Period
        Duration duration=Duration.ofDays(1);
        Period period=Period.between(LocalDate.of(2021,2,2),LocalDate.of(2021,2,5));
        LocalDateTime localDateTime14 = of1.plus(duration);
        LocalDateTime localDateTime15 = of1.plus(period);
        LocalDateTime localDateTime16 = of1.minus(duration);
        LocalDateTime localDateTime17 = of1.minus(period);
        System.out.println("of1 = " + formatDate(of1));
        System.out.println("localDateTime14 = " + formatDate(localDateTime14));
        System.out.println("localDateTime15 = " + formatDate(localDateTime15));
        System.out.println("localDateTime16 = " + formatDate(localDateTime16));
        System.out.println("localDateTime17 = " + formatDate(localDateTime17));

        System.out.println("----------------------------");

        /**
         * withDayOfMonth,   将月份天数、年份天数、月份、年份,时,分,秒
         * withDayOfYear,    修 改 为 指 定 的 值 并 返 回 新 的
         * withMonth,        LocalDate 对象
         * withYear,
         * withHour,
         * withMinute,
         * withSecond
         */
        LocalDateTime localDateTime18 = of1.withDayOfMonth(5);
        LocalDateTime localDateTime19 = of1.withDayOfYear(123);
        LocalDateTime localDateTime20 = of1.withHour(5);
        LocalDateTime localDateTime21 = of1.withYear(2025);
        LocalDateTime localDateTime22 = of1.withMonth(4);
        LocalDateTime localDateTime23 = of1.withHour(12);
        LocalDateTime localDateTime24 = of1.withMinute(34);
        LocalDateTime localDateTime25 = of1.withSecond(23);
        LocalDateTime localDateTime26 = of1.withNano(123);
        System.out.println("of1 = " +formatDate(of1));
        System.out.println("localDateTime18 = " + formatDate(localDateTime18));
        System.out.println("localDateTime19 = " + formatDate(localDateTime19));
        System.out.println("localDateTime20 = " + formatDate(localDateTime20));
        System.out.println("localDateTime21 = " + formatDate(localDateTime21));
        System.out.println("localDateTime22 = " + formatDate(localDateTime22));
        System.out.println("localDateTime23 = " + formatDate(localDateTime23));
        System.out.println("localDateTime24 = " + formatDate(localDateTime24));
        System.out.println("localDateTime25 = " + formatDate(localDateTime25));
        System.out.println("localDateTime26 = " + formatDate(localDateTime26));

        System.out.println("--------------------------");

        //getDayOfMonth 获得月份天数(1-31)
        int dayOfMonth = of1.getDayOfMonth();
        System.out.println("dayOfMonth = " + dayOfMonth);
        //getDayOfYear 获得年份天数(1-366)
        int dayOfYear = of1.getDayOfYear();
        System.out.println("dayOfYear = " + dayOfYear);
        //getDayOfWeek 获得星期几(返回一个 DayOfWeek枚举值)
        DayOfWeek dayOfWeek = of1.getDayOfWeek();
        int value = dayOfWeek.getValue();
        System.out.println("value = " + value);

        System.out.println("------------------------------");

        /**
         * getMonth() 获得月份-返回一个枚举值
         * getMonthValue 获得月份(1-12)
         * getHour() 获取时
         * getMinute() 获取分
         * getSecond() 获取秒
         */
        Month month = of1.getMonth();
        System.out.println("month.getValue() = " + month.getValue());
        int monthValue = of1.getMonthValue();
        System.out.println("monthValue = " + monthValue);
        int hour = of1.getHour();
        System.out.println("hour = " + hour);
        int minute = of1.getMinute();
        System.out.println("minute = " + minute);
        int second = of1.getSecond();
        System.out.println("second = " + second);

        System.out.println("-------------------------");

        /**
         * isBefore, isAfter 比较两个 LocalDate
         */
        LocalDateTime localDateTime27 = of1.withHour(14);
        System.out.println("of1 = " + formatDate(of1));
        System.out.println("localDateTime27 = " + formatDate(localDateTime27));
        System.out.println("of1.isBefore(localDateTime27) = " + of1.isBefore(localDateTime27));
        System.out.println("of1.isAfter(localDateTime27) = " + of1.isAfter(localDateTime27));

        System.out.println("--------------------------");

        /**
         * isLeapYear 判断是否是闰年--针对LocalDate时间类型
         */
        boolean leapYear = of.isLeapYear();
        System.out.println("of = " + of);
        System.out.println("leapYear = " + leapYear);
    }

2.Instant 时间戳

用于“时间戳”的运算。它是以Unix元年(传统的设定为UTC时区1970年1月1日午夜时分)开始所经历的描述进行运算

/**
     * Instant 时间戳
     * Instant.now()  初始化一个时区对象
     * ZoneId.systemDefault()  获取当前系统默认时区
     * ZoneOffset.UTC  获取UTC时区
     * LocalDateTime.ofInstant(instant,zone)  将时区转化为LocalDateTime,使用指定时区
     * instant.atOffset(ZoneOffset.ofHours(8)) 从当前时间戳对象偏移指定小时
     * Instant.ofEpochSecond(5) 从1970-01-01时间开始偏移5秒
     */
    @Test
    public void test2(){
        //默认使用UTC时区
        Instant instant = Instant.now();
        System.out.println("now = " + instant);
        //系统默认时区--此时为Asia/Shanghai
        ZoneId zone=ZoneId.systemDefault();
        System.out.println("zone = " + zone);
        LocalDateTime localDateTime=LocalDateTime.ofInstant(instant,zone);
        System.out.println("localDateTime = " + formatDate(localDateTime));
        //UTC时区
        LocalDateTime localDateTime1 = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
        System.out.println("localDateTime1 = " + formatDate(localDateTime1));
        //时区偏移8小时
        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
        System.out.println("offsetDateTime = " + offsetDateTime);
        //从1970-01-01时间开始偏移5秒
        Instant instant1 = Instant.ofEpochSecond(5);
        System.out.println("instant1 = " + instant1);
    }

3.Duration 和 Period

Duration:用于计算两个“时间”间隔
Period:用于计算两个“日期”间隔

/**
     * Duration:用于计算两个“时间”间隔
     * Period:用于计算两个“日期”间隔
     */
    @Test
    public void test3(){
        Instant instant = Instant.now();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Instant instant1 = Instant.now();

        Duration between = Duration.between(instant, instant1);
        System.out.println("between = " + between.getSeconds());

        LocalDate now = LocalDate.now();
        LocalDate of = LocalDate.of(2022, 3, 22);
        Period period = Period.between(now, of);
        System.out.println("period = " + period.getDays());
    }

4.日期的操纵

TemporalAdjuster : 时间校正器。有时我们可能需要获取例如:将日期调整到“下个周日”等操作。
TemporalAdjusters : 该类通过静态方法提供了大量的常用 TemporalAdjuster 的实现。

 /**
     * 时间校正器 TemporalAdjuster  根据当前时间获取特定的某个日期
     */
    @Test
    public void test4(){

        //当前月第一天
        LocalDateTime dateTime = LocalDateTime.now().with(TemporalAdjusters.firstDayOfMonth());
        System.out.println("date = " + formatDate(dateTime));

        //下一个周一
        LocalDateTime dateTime1 = LocalDateTime.now().with(TemporalAdjusters.next(DayOfWeek.MONDAY));
        System.out.println("dateTime1 = " + formatDate(dateTime1));
    }

5.解析与格式化

java.time.format.DateTimeFormatter 类:该类提供了三种格式化方法:
⚫ 预定义的标准格式
⚫ 语言环境相关的格式
⚫ 自定义的格式

 /**
     * DateTimeFormatter : 解析和格式化日期或时间
     */
    @Test
    public void test5(){
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime date = LocalDateTime.now();
        String format = dateTimeFormatter.format(date);
        System.out.println("format = " + format);
        LocalDateTime parse = LocalDateTime.parse(format, dateTimeFormatter);
        System.out.println("parse = " + parse);
    }

6.时区的处理

Java8 中加入了对时区的支持,带时区的时间为分别为:ZonedDate、ZonedTime、ZonedDateTime
其中每个时区都对应着 ID,地区ID都为 “{区域}/{城市}”的格式
例如 :Asia/Shanghai 等
ZoneId:该类中包含了所有的时区信息
getAvailableZoneIds() : 可以获取所有时区时区信息
of(id) : 用指定的时区信息获取ZoneId 对象

 /**
     * 带时区的时间为分别为:ZonedDate、ZonedTime、ZonedDateTime
     * of(id) : 用指定的时区信息获取ZoneId 对象
     * getAvailableZoneIds(): 获取所有的时区信息
     */
    @Test
    public void test6(){
        LocalDateTime localDateTime = LocalDateTime.now(ZoneId.of(ZoneId.systemDefault().toString()));
        System.out.println("localDateTime = " + formatDate(localDateTime));
        Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
        availableZoneIds.forEach(System.out::println);
    }

7.与传统日期处理的转换

在这里插入图片描述

/**
     * 传统时间格式与JDK8新时间格式转换
     *
     * 传统时间格式与新时间格式转换:通过Instant时间戳对象转换
     */
    @Test
    public void test7(){
        //Date->LocalDateTime
        Date date = new Date();
        Instant instant = date.toInstant();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        System.out.println("localDateTime = " + formatDate(localDateTime));

        //LocalDateTime->Date
        LocalDateTime localDateTime1 = LocalDateTime.now();
        ZonedDateTime zonedDateTime = localDateTime1.atZone(ZoneId.systemDefault());
        Date date1 = Date.from(zonedDateTime.toInstant());
        System.out.println("date1 = " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date1));
    }

6.接口中的默认方法与静态方法

1.接口中的默认方法

Java 8中允许接口中包含具有具体实现的方法,该方法称为“默认方法”,默认方法使用 default关键字修饰.

接口默认方法的”类优先”原则
若一个接口中定义了一个默认方法,而另外一个父类或接口中又定义了一个同名的方法时
⚫ 选择父类中的方法。如果一个父类提供了具体的实现,那么接口中具有相同名称和参数的默认方法会被忽略。

public interface MyInterface {

    default String getName(){
        return "王奎";
    }

    default void print(){
        System.out.println("接口中的默认方法");
    }
}

public class MyClass {
    public String getName(){
        return "刘先楼";
    }
}

public class SubClass extends MyClass implements MyInterface {

}

public class TestInterface {

    @Test
    public void test(){
        SubClass subClass=new SubClass();
        String name = subClass.getName();
        System.out.println("name = " + name);
    }
}

执行结果:
子类实例对象执行了父类中的getName()方法。
在这里插入图片描述

接口冲突。如果一个父接口提供一个默认方法,而另一个接口也提供了一个具有相同名称和参数列表的方法(不管方法是否是默认方法),那么必须覆盖该方法来解决冲突

public interface MyInterface {

    default String getName(){
        return "王奎";
    }

    default void print(){
        System.out.println("接口中的默认方法");
    }
}

public interface MyInterface2 {

    public String getName();

}

public class SubClass /*extends MyClass*/ implements MyInterface,MyInterface2 {

    @Override
    public String getName() {
        return "张志忠";
    }
}

public class TestInterface {

    @Test
    public void test(){
        SubClass subClass=new SubClass();
        String name = subClass.getName();
        System.out.println("name = " + name);
    }
}

执行结果:
子类覆盖父接口中的getName()方法,来解决冲突。
在这里插入图片描述

2.接口中的静态方法

Java8 中,接口中允许添加静态方法。

接口中的静态方法不能使用protected,default 访问修饰符

public interface MyInterface {

    default String getName(){
        return "王奎";
    }
	//default 类权限修饰符不能用来修饰静态方法
    default static void print(){
        System.out.println("接口中的默认方法");
    }
    //protected 类权限修饰符不能用来修饰静态方法
     protected static void print4(){
        System.out.println("接口中的静态方法");
    }
    
    static void print2(){
        System.out.println("接口中的静态方法");
    }

	public static void print3(){
        System.out.println("接口中的静态方法");
    }  
    private static void print5(){
        System.out.println("接口中的静态方法");
    }
}

7.其他新特性

1.Optional 类

Optional 类(java.util.Optional) 是一个容器类,代表一个值存在或不存在,原来用 null 表示一个值不存在,现在 Optional 可以更好的表达这个概念。并且可以避免空指针异常。
常用方法:
Optional.of(T t) : 创建一个 Optional 实例
Optional.empty() : 创建一个空的 Optional 实例
Optional.ofNullable(T t):若 t 不为 null,创建 Optional 实例,否则创建空实例
isPresent() : 判断是否包含值
orElse(T t) : 如果调用对象包含值,返回该值,否则返回t
orElseGet(Supplier s) :如果调用对象包含值,返回该值,否则返回 s 获取的值
map(Function f): 如果有值对其处理,并返回处理后的Optional,否则返回 Optional.empty()
flatMap(Function mapper):与 map 类似,要求返回值必须是Optional

    /**
     * Optional.of(T t) : 创建一个 Optional 实例
     */
    @Test
    public void test(){
        Optional<Employee> employee = Optional.of(new Employee());
        Employee employee1 = employee.get();
        System.out.println("employee1 = " + employee1);
    }


    /**
     * Optional.empty() : 创建一个空的 Optional 实例
     * Optional.ofNullable(T t):若 t 不为 null,创建 Optional 实例,否则创建空实例
     */
    @Test
    public void test1(){
        Optional<Object> empty = Optional.empty();
        Object o = empty.get();
        System.out.println("o = " + o);
        Optional<Object> o1 = Optional.ofNullable(null);
        Object o2 = o1.get();
        System.out.println("o2 = " + o2);
    }

    /**
     * isPresent() : 判断是否包含值
     * orElse(T t) : 如果调用对象包含值,返回该值,否则返回t
     * orElseGet(Supplier s) :如果调用对象包含值,返回该值,否则返回 s 获取的值
     */
    @Test
    public void test2(){
        Optional<Employee> employee = Optional.of(new Employee());
        if (employee.isPresent()) {
            Employee employee1 = employee.get();
            System.out.println("employee1 = " + employee1);
        }
        Employee employee1 = employee.orElse(new Employee("张飒"));

        Employee employee2 = employee.orElseGet(Employee::new);
    }

    /**
     * map(Function f): 如果有值对其处理,并返回处理后的Optional,否则返回 Optional.empty()
     * flatMap(Function mapper):与 map 类似,要求返回值必须是Optional
     */
    @Test
    public void test3(){
        Optional<Employee> employee = Optional.of(new Employee(1, "王论悟", 32, 999.99));
        Optional<String> name = employee.map(Employee::getName);
        Optional<String> name1 = employee.flatMap((e) -> Optional.of(e.getName()));
    }
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Man {
    private String name;
    private Goddess goddess;
}

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Goddess {
    private String name;
}
 @Test
    public void test4(){
       Goddess goddess=new Goddess("高圆圆");
       Man man=new Man("赵又廷",goddess);
        String goddessName = getGoddessName(man);
    }
    private String getGoddessName(Man man){
        String name="";
        if (!Objects.isNull(man)) {
            Goddess goddess = man.getGoddess();
            if (!Objects.isNull(goddess)) {
                 name = goddess.getName();
            }
        }
        return name;
    }
//注意:Optional 不能被序列化

@Data
@NoArgsConstructor
@AllArgsConstructor
public class NewMan {
    private String name;
    private Optional<Goddess> goddess=Optional.empty();

    private Goddess god;

    public Optional<Goddess> getGod(){
        return Optional.of(god);
    }

}

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Goddess {
    private String name;
}

    @Test
    public void test5(){
        NewMan newMan=new NewMan("周芷若",Optional.of(new Goddess()),null);
        String goddessName2 = getGoddessName2(Optional.ofNullable(newMan));
        System.out.println("goddessName2 = " + goddessName2);
    }

    private String getGoddessName2(Optional<NewMan> newMan){
        return newMan.orElse(new NewMan())//NewMan对象为null时,初始化一个默认的实例
                .getGoddess()
                .orElse(new Goddess("高圆圆"))//Goddess对象为null时,初始化一个默认的实例
                .getName();

    }

2.重复注解与类型注解

Java 8对注解处理提供了两点改进:可重复的注解及可用于类型的注解。

1.重复注解:

允许在同一申明类型(类,属性,或方法)前多次使用同一个类型注解。
在java8 以前,同一个程序元素前最多只能有一个相同类型的注解;如果需要在同一个元素前使用多个相同类型的注解,则必须使用注解“容器”。

public @interface Authority {
     String role();
}

public @interface Authorities {   //@Authorities注解作为可以存储多个@Authority注解的容器
    Authority[] value();
}

public class RepeatAnnotationUseOldVersion {
    @Authorities({@Authority(role="Admin"), @Authority(role="Manager")})
    public void doSomeThing(){
    }
}

java8 新增了重复注解,其使用方式为:

@Repeatable(Authorities.class)
public @interface Authority {
     String role();
}

public @interface Authorities {
    Authority[] value();
}

public class RepeatAnnotationUseNewVersion {
    @Authority(role="Admin")
    @Authority(role="Manager")
    public void doSomeThing(){ }
}

不同的地方是,创建重复注解 Authority 时,加上@Repeatable,指向存储注解 Authorities,在使用时候,直接可以重复使用 Authority 注解。从上面例子看出,java 8里面做法更适合常规的思维,可读性强一点。但是,仍然需要定义容器注解。

两种方法获得的效果相同。重复注解只是一种简化写法,这种简化写法是一种假象:多个重复注解其实会被作为“容器”注解的 value 成员的数组元素处理。

2.类型注解

Java8 为 ElementType 枚举增加了TYPE_PARAMETER、TYPE_USE两个枚举值,从而可以使用 @Target(ElementType_TYPE_USE) 修饰注解义,这种注解被称为类型注解,可以用在任何使用到类型的地方。

在 java8 以前,注解只能用在各种程序元素(定义类、定义接口、定义方法、定义成员变量…)上。从 java8 开始,类型注解可以用在任何使用到类型的地方。

TYPE_PARAMETER:表示该注解能写在类型参数的声明语句中。 类型参数声明如: <T>、<T extends Person>
TYPE_USE:表示注解可以再任何用到类型的地方使用,比如允许在如下位置使用:

  • 创建对象(用 new 关键字创建)
  • 类型转换
  • 使用 implements 实现接口
  • 使用 throws 声明抛出异常
@Target(ElementType.TYPE_USE)
@interface NotNull{

}

// 定义类时使用
// 在implements时使用
@NotNull
public class TypeAnnotationTest implements Serializable {

    // 在方法形参中使用
    // 在throws时使用
    public static void main(@NotNull String [] args) throws @NotNull FileNotFoundException {

        Object  obj = "fkjava.org";

        // 使用强制类型转换时使用
        String str = (@NotNull String) obj;

        // 创建对象时使用
        Object win = new (@NotNull) JFrame("疯狂软件");   
    } 

    // 泛型中使用
    public void foo(List<@NotNull String> info) {

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值