java自定义注解,步骤明确

注解注意点:

  • 注解只能作用于注解类型元素(aanotation type element),包括:基本数据类型(int…)、String、Class、枚举类型、注解类型,及其一维数组。
  • 注解定义的语法比较奇怪,这是为了表示其即能当做属性赋值,又能够当做方法调用,表现为:()不是定义方法参数的地方,也不能在括号中定义任何参数
  • 注解的省略:
    • 数组只有一个元素时,可以省略{}
    • 注解有默认参数时,可以省略。
    • 只有一个名为value()的注解时,对其赋值时可以省略value,只写常量。

注解步骤:

  1. 添加元注解:@Retention(RetentionPolicy.RUNTIME) 必不可少。@Target(value = ElementType.METHOD)
  2. 判断类中否是存在指定注解:xxx.isAnnotationPresent()配置在谁上,就在谁上获取:Class.getAnnotation(Class)/Field.getAnnotation(Class)/Method.getAnnotation(Class)/Constructor.getAnnotation(Class)
  3. 获取相应的注解类,然后使用:getAnnotation

实例

1. 定义注解。
package yyq.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(value = ElementType.METHOD)
public @interface MethodAnnotation {
    String name() default "zhangsan";
    int age() default 18;
    int[] array();
}

2.使用注解。
package yyq.annotation;

public class Person {
    @MethodAnnotation(name = "Person ",age=30,array = {53,77})
    public void printName(int N){
        for(int i=0;i<N;i++){
            System.out.println("my name is zhangsan");
        }
    }
}
3.解析注解(放在另外一个类中)。
package yyq.annotation;

import java.lang.reflect.Method;

public class TestAnnotation {
    public static void main(String[] args){
        try{
            Class personClass=Class.forName("yyq.annotation.Person");
            Method personMethod=personClass.getMethod("printName", int.class);//配置在谁上,就在谁上获取
            if(personMethod.isAnnotationPresent(MethodAnnotation.class)){//先判断是否存在
                System.out.println("Persoin类上配置了MethodAnnotation注解");
                MethodAnnotation methodAnnotation =personMethod.getAnnotation(MethodAnnotation.class);//使用
                System.out.println("name="+ methodAnnotation.name()+", age: "+ methodAnnotation.age()+" ,score:"+ methodAnnotation.array()[0]);
            }
        }catch (ClassNotFoundException | NoSuchMethodException e){
            e.printStackTrace();
        }


    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值