Java 注解学习

1.常见注解

jdk注解

1.@Override 2.@Deprecated 3.@Suppvisewarnings

1.表示方法的复写
2.表示方法已经过时
3.这个仅仅是告诉编译器忽略特定的警告信息,例如在泛型中使用原生数据类型。它的保留策略是SOURCE(译者注:在源文件中有效)并且被编译器丢弃。

第三方注解

2.注解分类

1.源码注解

注解只在源码中存在,编译成class文件就不存在了。

2.编译时注解

在class文件中,还会存在的注解

3.运行时注解

在运行阶段还起作用,甚至会影响运行逻辑的注解

4.元注解

注解的注解

3.自定义注解

1.自定义注解的语法要求

注:注解方法无参无异常
//元注解
@Target({ElementType.METHOD,ElementType.TYPE})//target注解作用域
@Retention(RetentionPolicy.RUNTIME)//生命周期
@Inherited//允许子类继承
@Documented//生成javadoc包含注解
//使用@interface关键字定义注解
public @interface Description {

	//注解只有一个成员的时候,成员名必须取名为value(),在使用时可以忽略成员名和赋值号(=)
	String desc();
	
	String author();
	
	int age() default 18;
}

2.使用自定义注解

//使用注解语法:
	//@<注解名>(<成员名1>=<成员值1>,<成员名1>=<成员值1>,...)
	@Description(desc="I am eyeColor",author="boy",age=18)
	public String eyeColor(){
		return "red";
		
	}

3.解析注解

1.修改后的注解
//元注解
@Target({ElementType.METHOD,ElementType.TYPE})//target注解作用域
@Retention(RetentionPolicy.RUNTIME)//生命周期
@Inherited//允许子类继承
@Documented//生成javadoc生成注解信息
//使用@interface关键字定义注解
public @interface Description {

	//注解只有一个成员的时候,成员名必须取名为value(),在使用时可以忽略成员名和赋值号(=)
	String value();
}
2.注解测试类
@Description("i am class annotation")
public class test {

	//使用注解语法:
	//@<注解名>(<成员名1>=<成员值1>,<成员名1>=<成员值1>,...)
	@Description("i am method annotation")
	public String eyeColor(){
		return "red";
		
	}
}

3.main中解析注解
	public static void main(String[] args) {
		//1.使用类加载器加载类
		try {
			Class clazz=Class.forName("test.test");
			//2.找到类上面的注解
			boolean isExist=clazz.isAnnotationPresent(Description.class);
			if(isExist){
				//3.拿到注解实例
				Description d=(Description) clazz.getAnnotation(Description.class);
				System.out.println(d.value());
			}
			//4.找到方法上的注解
			Method[]ms=clazz.getMethods();
			for(Method m:ms){
				boolean isMExist=m.isAnnotationPresent(Description.class);
				if(isMExist){
					//拿到注解
					Description d=(Description) m.getAnnotation(Description.class);
					System.out.println(d.value());
				}
			}
			
			//另一种解析
			for(Method m:ms){
				Annotation[]as=m.getAnnotations();
				for(Annotation a:as){
					if(a instanceof Description){
						System.out.println(((Description) a).value());
					}
				}
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

注@Inherited只能继承类上面的注解,不能继承接口以及方法注解

当将@Retention(RetentionPolicy.RUNTIME)//生命周期改成Source和class的时候运行时并不能起到作用


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值