Java--注解

1 Java定义的基本注解
@Overide 检查父类中有无被修饰的方法。
@Deprecated 标记为已过时。
@SuppressWarnings 抑制编译警告
@SafeVarargs
堆污染:将一个不带泛型的对象赋给了一个带泛型的变量,往往会出现堆污染。会出现警告,该注解抑制该警告
@FunctionalInterface 用来指定某个接口必须是函数式接口。

2 自定义注解

//使用如下注解后,定义的注解才会在JVm运行时装载.class时读取修饰的注解信息
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {

    String name() default "dema";

    int age() default 1;

注意:一定要添加@Retention(RetentionPolicy.RUNTIME)。
添加到一个方法中:

public class TextAnnotation {

    @MyAnnotation(name="dema",age=10)
    public void getInfo(){
        System.out.println("run in getInfo"); 
    }
}

测试:获取注解上的值信息。

public static void text02() throws NoSuchMethodException,
            SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Class<?> clazz = Class
        .forName("com.text.annotation.TextAnnotation");
        Method method = clazz.getMethod("getInfo");
        Annotation[] annArray = method.getAnnotations();//获取该方法上的注解信息
        for (Annotation annotation : annArray) {
            if(annotation instanceof MyAnnotation){
                //获取该注解成员值
                System.out.println(((MyAnnotation)annotation).name()+"  "+((MyAnnotation)annotation).age());
            }
        }
    }

结果:
这里写图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值