Java8新特性
Java9新特性

Java8新特性注解

增加了FunctionalInterface注解

函数式接口注解,为Labmda表达式准备的。

当接口中只有一个方法是抽象方法时,则该接口可以声明为函数式接口。

package com.wkcto.annotaitons;

/**
 * 函数式接口
 * Author : 动力节点老崔
 */
@FunctionalInterface            //注解声明接口为函数式接口
public interface MyInterface2 {
    void  m1();

    default void dm(){
        System.out.println("default修饰的方法有默认方法体");
    }
}
package com.wkcto.annotaitons;

/**
 * 函数式接口可以使用Labmda表达式
 * Author : 动力节点老崔
 */
public class Test01 {
    public static void main(String[] args) {
        //接口赋值匿名内部类对象
        MyInterface2  mi2 = new MyInterface2() {
            @Override
            public void m1() {
                System.out.println("在匿名内部类中重写接口的抽象方法");
            }
        };
        mi2.m1();       //执行匿名内部类对象的方法

        //MyInteface2接口声明为了函数式接口,可以直接给接口引用赋值Labmda表达式
        mi2 = () -> System.out.println("给接口引用赋值Lambda表达式");
        mi2.m1();

    }
}

对元注解的增强

JDK8扩展了注解的使用范围,在ElementType枚举类型中增强了两个枚举值:

ElementType.PARAMETER,表示注解能写在类型变量的声明语句中。

ElementType.USE, 表示注解能写在使用类型的任何语句中。

增加了Repeatable元注解.JDK8前的版本中,同一个注解在同一个位置只能使用一次,不能使用多次. 在JDK8中引入了重复注解,表示一个注解在同一个位置可以重复使用多次。

package com.wkcto.annotaitons;

import java.lang.annotation.*;

/**自定义可重复的注解
 * Author : 动力节点老崔
 */
@Repeatable(RoleAnnotions.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD})
public @interface MyAnnotation {
    String role();      //定义角色属性
}
package com.wkcto.annotaitons;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 定义一个容器,可以包含若干的MyAnnotation注解
 * Author : 动力节点老崔
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD})
public @interface RoleAnnotions {
    MyAnnotation[] value();
}
package com.wkcto.annotaitons;

/**
 * 使用重复注解修饰一个类
 * Author : 动力节点老崔
 */
@MyAnnotation( role = "Husband")
@MyAnnotation(role = "Son")
@MyAnnotation(role = "Father")
public class Person {
}
package com.wkcto.annotaitons;

/**
 * 通过反射读取可重复注解的信息
 * Author : 动力节点老崔
 */
public class Test02 {
    public static void main(String[] args) {
        //创建Class对象
        Class<?> claxx = Person.class;

        //获得指定的自定义注解
        MyAnnotation[] myAnnotations = claxx.getDeclaredAnnotationsByType(MyAnnotation.class);
        //遍历数组,打印角色属性
        for (MyAnnotation  annotation : myAnnotations){
            System.out.println( annotation.role());
        }
    }
}

 

全部教程