注解类的定义和使用

定义注解类

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

@Target({ElementType.FIELD,ElementType.METHOD})//作用目标,字段,方法
@Retention(RetentionPolicy.RUNTIME)//作用范围,整个运行期间
public @interface AnnotionBase {
//定义int型字段,id,默认值为3
    int id() default 3;
// 定义string类型的数组,stValue
    String[] stValue();
}

反射获取属性

package com.ny;

import com.ny.base.annotion.AnnotionBase;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.SQLOutput;

public class App {
    @AnnotionBase(stValue = {"male", "female"})
    public void getUser(String name, int age) {
        System.out.println("user: [" + name + "," + age + "]");
    }
    @AnnotionBase(id = 3, stValue = {"kj"})
    public int age;

    public static void main(String[] args) throws Exception {
        App app = new App();
        Class<? extends App> aClass = app.getClass();

        Field age = aClass.getField("age");
        AnnotionBase annotation1 = age.getAnnotation(AnnotionBase.class);
        System.out.println(annotation1.id()+"id");
        for (String s : annotation1.stValue()) {
            System.out.println("stValue"+s);
        }

        Method getUser = aClass.getMethod("getUser", String.class, int.class);
        getUser.invoke(app,"ff",3);

        AnnotionBase annotation = getUser.getAnnotation(AnnotionBase.class);
        String[] strings = annotation.stValue();
        for (String string : strings) {
            System.out.println(string);
        }
        System.out.println(annotation.id());

    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值