反射获取属性和方法的注解

package com.chixing.day16.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ParseAnnotation {
    public static void main(String[] args) {
        //获得AnnotationDemo中的字段与注解的详细信息
        //1.类加载
        Class<AnnotationDemo> clazz = com.chixing.day16.annotation.AnnotationDemo.class;
        //2.获取字段
        Field[] field = clazz.getDeclaredFields();
        for (Field f : field) {
            //字段名
            String fName = f.getName();
            //字段权限
            int fModifiers = f.getModifiers();
            //字段类型
            Class fType = f.getType();
            System.out.println("字段名:" + fName + " 字段权限:" + fModifiers + " 字段类型:" + fType);
            //获取字段的注解
            Annotation[] annotations = f.getDeclaredAnnotations();
            for (Annotation a : annotations) {
                System.out.println(f.getName()+"字段上有注释:"+a);
            }
        }
        //获取方法
        Method[] method = clazz.getDeclaredMethods();
        for (Method m : method){
            //获取注解
            Annotation[] annotations = m.getDeclaredAnnotations();
            for (Annotation a : annotations){
                System.out.println(m.getName()+"方法上有注释:"+a);
            }
        }
    }
}

注解的内容

package com.chixing.day16.annotation;

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

@Target({ElementType.METHOD,ElementType.FIELD})//注解的作用范围
@Retention(RetentionPolicy.RUNTIME)//注解的作用时长,运行时保留
public @interface Mymessage {
    String name() default "sam";

    int num() default 0;

    String desc();
}

示例

package com.chixing.day16.annotation;

public class AnnotationDemo {
    @Mymessage(num = 10,name = "a",desc = "静态变量a")
    private static int a = 10;
    @Mymessage(name = "add",desc = "类中的一个普通方法")
    public void add(){

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值