Java8接口默認靜態(tài)方法及重復注解原理解析
更新時間:2020年04月03日 08:26:05 作者:moyuduo
這篇文章主要介紹了Java8接口默認靜態(tài)方法及重復注解原理解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
接口默認方法和靜態(tài)方法
默認方法
interface MyInterface1 {
default String method1() {
return "myInterface1 default method";
}
}
class MyClass{
public String method1() {
return "myClass method";
}
}
/**
* 父類和接口中都有相同的方法,默認使用父類的方法,即類優(yōu)先
* @author 莫雨朵
*
*/
class MySubClass1 extends MyClass implements MyInterface1{
}
@Test
public void test1() {
MySubClass1 mySubClass1=new MySubClass1();
System.out.println(mySubClass1.method1());//myClass method
}
如果類的父類的方法和接口中方法名字相同且參數一致,子類還沒有重寫方法,那么默認使用父類的方法,即類優(yōu)先
interface MyInterface1 {
default String method1() {
return "myInterface1 default method";
}
}
interface MyInterface2 {
default String method1() {
return "myInterface2 default method";
}
}
/**
* 如果類實現的接口中有名字相同參數類型一致的默認方法,那么在類中必須重寫
* @author 莫雨朵
*
*/
class MySubClass2 implements MyInterface1,MyInterface2{
@Override
public String method1() {
return MyInterface1.super.method1();
}
}
@Test
public void test2() {
MySubClass2 mySubClass2=new MySubClass2();
System.out.println(mySubClass2.method1());//myInterface1 default method
}
如果類實現的接口中有名字相同參數類型一致的默認方法,那么在類中必須重寫
靜態(tài)方法
interface MyInterface1 {
static String method2() {
return "interface static method";
}
}
@Test
public void test3() {
System.out.println(MyInterface1.method2());//interface static method
}
重復注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MAnnotation {
String name() default "";
int age();
}
public class AnnotataionTest {
@Test
public void test() throws Exception {
Class<AnnotataionTest> clazz=AnnotataionTest.class;
Method method = clazz.getMethod("good", null);
MAnnotation annotation = method.getAnnotation(MAnnotation.class);
System.out.println(annotation.name()+":"+annotation.age());
}
@MAnnotation(name="tom",age=20)
public void good() {
}
}
以前我們是這樣使用注解,當要在一個方法上標注兩個相同的注解時會報錯,java8允許使用一個注解來存儲注解,可以實現一個注解重復標注
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Repeatable(MAnnotations.class)//使用@Repeatable來標注存儲注解的注解
public @interface MAnnotation {
String name() default "";
int age();
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MAnnotations {
MAnnotation[] value();
}
public class AnnotataionTest {
@Test
public void test() throws Exception {
Class<AnnotataionTest> clazz=AnnotataionTest.class;
Method method = clazz.getMethod("good");
MAnnotation[] mAnnotations = method.getAnnotationsByType(MAnnotation.class);
for (MAnnotation annotation : mAnnotations) {
System.out.println(annotation.name()+":"+annotation.age());
}
}
@MAnnotation(name="tom",age=20)
@MAnnotation(name="jack",age=25)
public void good() {
}
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
相關文章
mybatisplus?@Select注解中拼寫動態(tài)sql異常問題的解決
這篇文章主要介紹了mybatisplus?@Select注解中拼寫動態(tài)sql異常問題的解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12

