当前位置: 移动技术网 > IT编程>开发语言>Java > java8接口默认方法静态方法和重复注解

java8接口默认方法静态方法和重复注解

2020年04月03日  | 移动技术网IT编程  | 我要评论

四喜豆腐是哪里的菜系,fantasyxrunners,028成都交友网

接口默认方法和静态方法

默认方法

interface myinterface1 {

	default string method1() {
		return "myinterface1 default method";
	}
}

class myclass{
	public string method1() {
		return "myclass method";
	}
}

/**
 * 父类和接口中都有相同的方法,默认使用父类的方法,即类优先
 * @author 莫雨朵
 *
 */
class mysubclass1 extends myclass implements myinterface1{

}

@test
public void test1() {
  mysubclass1 mysubclass1=new mysubclass1();
  system.out.println(mysubclass1.method1());//myclass method
}

如果类的父类的方法和接口中方法名字相同且参数一致,子类还没有重写方法,那么默认使用父类的方法,即类优先

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
}

如果类实现的接口中有名字相同参数类型一致的默认方法,那么在类中必须重写

静态方法

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() {
		
	}
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网