JavaSE_注解(3)自定义注解和元注解的语法和基本使用

自定义注解
(1) 声明
(2)使用
(3)读取

①声明注解
格式:
[修饰符] @interface 注解名{
}
②使用注解
使用的位置:需要在声明注解的时候用@Target来注解注解能够使用的位置
③读取注解
特别说明,如果要用反射读取某个注解,那么对这个注解的声明的时候,一定要增加这个注解的元注解(@Retention(RetentionPolicy.RUNTIME))也是采用的是枚举的方法.

public class TestDefineAnnotation {
	//可以在类前使用自定义注解
@MyAnnotation
class MyClass{
	//在属性前使用自定义注解
	@MyAnnotation
	private int i;
	//在方法前使用自定义注解
	@MyAnnotation
	public  void test() {
		
	}
	
}
	//声明注解
	@java.lang.annotation.Target({  FIELD, METHOD,TYPE })
@Retention(RUNTIME)
	@interface MyAnnotation{
		
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		Class  clazz = MyClass.class;
		MyAnnotation my = (MyAnnotation)clazz.getAnnotation(MyAnnotation.class);
		System.out.println(my);
	}

}

用反射得到注解
在这里插入图片描述

元注解
用于给注解加的注解.
1.@Target(xx):
用来标记这个注解可以用在xx位置
这个位置由ElementType枚举常量对象来指定
2.注解有生命周期
@Retention(xx)
表示注解能够滞留到什么阶段.
如果想被反射读取到,必须将生命周期提高到运行时(RUNTIME)
这个生命周期由RetentionPolicy枚举的常量对象来指定.(SOURCE-源代码).(CLASS - 字节码阶段).(RUNTIME -运行时阶段)
3.@Documented
作用:标记这个注解是否可以被javadoc.exe读取到API中
4.@Inherited
作用:标记这个注解是否可以被子类继承,有这个元注解表示可以被子类继承,没有这个元注解表示不能被子类继承

注解参数配置
1.如何配置参数
格式:
[修饰符] @interface 注解名{
数据类型 配置参数名();
}
2.注解声明时有配置参数,那么在使用这个参数的时,要求给这个参数赋值.
如果配置参数的个数只有一个,并且名字叫valu,那么可以忽略"配置参数名="

标准的赋值格式:@注解名 (配置参数名 =参数值1,配置参数名=参数值2)
3.**配置参数如果有默认值,那么可以不赋值

总结 default
(1)switch
(2)接口默认方法
(3)自定义注解配置参数名

public class TestAnnotation {
	
	@interface MyAnnotation{
		String info();
	}
@MyAnnotation(info = "abc")
class MyClass1{
	@Test
	public void start() {
		System.out.println("开始测试");
	}
}			
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO 自动生成的方法存根

		Class clazz1 =MyClass.class;
		MyAnnotation my1 = (MyAnnotation)clazz1.getAnnotation(MyAnnotation.class);
		System.out.println(my1);
	}

}

静态导入
(1)import 包.类名
(2)import 包.*
(3)import static 包.类名.静态成员
(4) import static 包.类名.*

import static java.lang.Math.*;


	public static void main(String[] args) {
		Class clazz1 =MyClass.class;
		MyAnnotation my1 = (MyAnnotation)clazz1.getAnnotation(MyAnnotation.class);
		System.out.println(my1)	;			
		//静态导入
//		静态导入了   注意是静态的导入java.lang.Math.*;
		//所以用PI sqrt都可以直接用
		System.out.println(PI);
		System.out.println(sqrt(6));
	}
发布了82 篇原创文章 · 获赞 26 · 访问量 3996

猜你喜欢

转载自blog.csdn.net/qq_40742223/article/details/104570414