增加了FunctionalInterface注解
函數(shù)式接口注解,為Labmda表達(dá)式準(zhǔn)備的。
當(dāng)接口中只有一個(gè)方法是抽象方法時(shí),則該接口可以聲明為函數(shù)式接口。
package com.wkcto.annotaitons;
/**
* 函數(shù)式接口
* Author : 動(dòng)力節(jié)點(diǎn)老崔
*/
@FunctionalInterface //注解聲明接口為函數(shù)式接口
public interface MyInterface2 {
void m1();
default void dm(){
System.out.println("default修飾的方法有默認(rèn)方法體");
}
}
package com.wkcto.annotaitons;
/**
* 函數(shù)式接口可以使用Labmda表達(dá)式
* Author : 動(dòng)力節(jié)點(diǎn)老崔
*/
public class Test01 {
public static void main(String[] args) {
//接口賦值匿名內(nèi)部類對象
MyInterface2 mi2 = new MyInterface2() {
@Override
public void m1() {
System.out.println("在匿名內(nèi)部類中重寫接口的抽象方法");
}
};
mi2.m1(); //執(zhí)行匿名內(nèi)部類對象的方法
//MyInteface2接口聲明為了函數(shù)式接口,可以直接給接口引用賦值Labmda表達(dá)式
mi2 = () -> System.out.println("給接口引用賦值Lambda表達(dá)式");
mi2.m1();
}
}
對元注解的增強(qiáng)
JDK8擴(kuò)展了注解的使用范圍,在ElementType枚舉類型中增強(qiáng)了兩個(gè)枚舉值:
ElementType.PARAMETER,表示注解能寫在類型變量的聲明語句中。
ElementType.USE, 表示注解能寫在使用類型的任何語句中。
增加了Repeatable元注解.JDK8前的版本中,同一個(gè)注解在同一個(gè)位置只能使用一次,不能使用多次. 在JDK8中引入了重復(fù)注解,表示一個(gè)注解在同一個(gè)位置可以重復(fù)使用多次。
package com.wkcto.annotaitons;
import java.lang.annotation.*;
/**自定義可重復(fù)的注解
* Author : 動(dòng)力節(jié)點(diǎn)老崔
*/
@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;
/**
* 定義一個(gè)容器,可以包含若干的MyAnnotation注解
* Author : 動(dòng)力節(jié)點(diǎn)老崔
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD})
public @interface RoleAnnotions {
MyAnnotation[] value();
}
package com.wkcto.annotaitons;
/**
* 使用重復(fù)注解修飾一個(gè)類
* Author : 動(dòng)力節(jié)點(diǎn)老崔
*/
@MyAnnotation( role = "Husband")
@MyAnnotation(role = "Son")
@MyAnnotation(role = "Father")
public class Person {
}
package com.wkcto.annotaitons;
/**
* 通過反射讀取可重復(fù)注解的信息
* Author : 動(dòng)力節(jié)點(diǎn)老崔
*/
public class Test02 {
public static void main(String[] args) {
//創(chuàng)建Class對象
Class<?> claxx = Person.class;
//獲得指定的自定義注解
MyAnnotation[] myAnnotations = claxx.getDeclaredAnnotationsByType(MyAnnotation.class);
//遍歷數(shù)組,打印角色屬性
for (MyAnnotation annotation : myAnnotations){
System.out.println( annotation.role());
}
}
}