注解的基本使用(一)@Target(ElementType.TYPE、METHOD、FIELD)三个作用域的示例

本文介绍了Java注解的基本使用,重点讲解了@Target元注解在类(TYPE)、方法(METHOD)、字段(FIELD)三个作用域的示例。通过创建和测试ClassAnnotation、MethodAnnotation、FieldAnnotation三个注解类,以及相关测试用例,展示了如何获取不同位置的注解信息。

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

   四大元注解:

           1.@Target,2.@Retention,3.@Documented,4.@Inherited,具体介绍就不详解,可以自行百度。    

        代码实现:

            3个注解类:ClassAnnotation.java、MethodAnnotation.java、FieldAnnotation.java

            1个测试类:Test.java

            1个测试实体类:myName.java

        注解类代码

        1.ClassAnnotation.java详细代码:

        

        2.MethodAnnotation.java详细代码:

       

        3.FieldAnnotation.java详细代码:

        

        4,测试案例代码:        

         

测试代码:          

package myUnits_time;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
@ClassAnnotation(age=25)
public class Test {
 /**
  * Class注解测试
  * @param c
  */
 public static void test1(Class<?> c){
  ClassAnnotation ca = (ClassAnnotation) c.getAnnotation(ClassAnnotation.class);
  if (ca==null){
   System.out.println("UnKnown!!");
  }else{
   System.out.println(" age:"+ca.age());
  }
 }
 /**
  * Method注解测试
  * @param c
  *
  */
 public static void test2(Class<?> c){
  Method[] method = c.getDeclaredMethods();
  for(Method me :method){
   MethodAnnotation mothod = me.getAnnotation(MethodAnnotation.class);
   if (mothod == null){
    System.out.println("UnKnown!!");
   }else{
    System.out.println(mothod.name());
    System.out.println(mothod.value());
   }
  }
 }
 /**
  * Field注解测试
  * @param c
  */
 public static void test3(Class<?> c){
  Field[] field = c.getDeclaredFields();
  System.out.println("被注解FieldAnnotation注解的属性:");
  for(Field f : field){
   System.out.println("-----------------------------------");
   System.out.println("属性名称:"+f.getName()); 
   descFiledInfo(f);
  }
 }
 /**
  * 分别获取注解的详细信息
  * @param field
  */
 private static void descFiledInfo(Field field){
  FieldAnnotation fa = field.getAnnotation(FieldAnnotation.class);
  if (fa == null){
   System.out.println("UnKnown!!");
  }else{
   
   System.out.println(fa.name());
   System.out.println(fa.description());
  }
 }
 public static void main(String[] args) {
  Test.test1(Test.class);
  System.out.println("===================================");
  Test.test2(myName.class); 
  System.out.println("===================================");
  Test.test3(myName.class);
 }
}

结果显示:

这只是简单注解的使用,可以帮助理解;

简单说明:

注解作用在类上:用类名可以直接点出getAnnotation(xxx.class)方法,方法参数可以直接填写注解那个类;

注解作用在方法上:用类名可以直接点出getDeclaredMethods()方法,获取所有用注解注释的方法名称,在通过所得到的方法名称来获取对应的注解类;

注解作用在属性上:用类名可以直接点出c.getDeclaredFields()方法,获取所有用注解注释的属性名称,在通过所得到属性名称来获取对应的注解类;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值