Annotation的基本使用

本文介绍了Java中三种内置注解的功能与使用方法,包括@Override用于标记重写的方法,@Deprecated标识废弃的方法或类,以及@SuppressWarnings用于抑制警告信息。此外,还详细说明了如何自定义注解,并通过反射机制来调用这些注解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    三种内定的Annotation

1,@Override    声明方法是重写的

2,@Deprecated    声明已过时的方法或类

3,@SuppressWarnings   压制警告信息,里面可以是数组类型,{deprecation,unchecked,fallthrough,path,serial,finnally,all}

 

自定义Annotation

@Documented //文档注释
@Inherited //继承的类也继承注解
@Target(value={ElementType.TYPE,ElementType.METHOD,ElementType.FIELD}) //设置注解作用的地方,type为类
@Retention(RetentionPolicy.RUNTIME) //指定在运行时也起作用
public @interface TestAnno {
 public String value() default "aa";
 public int key() default 1;
 public my tt() default my.asd;
}

 

可以通过反射机制调用

Class<?> class1=Class.forName("com.bean.Student");
  @SuppressWarnings("all")
  Method method=class1.getMethod("say", null);
  Annotation[] annotations=method.getAnnotations();
  for (Annotation annotation : annotations) {
   
   if(annotation instanceof TestAnno){
    TestAnno ts=(TestAnno)annotation;
    System.out.println(ts.key());
   }
   
   
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值