java高级开发--注解Annotation

本次我们先来看JDK提供的三个内置注解:@Override、@Deprecated、@SuppressWarnings

package com.bit.annotation;

import java.io.Serializable;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: wang
 * Date: 2019-05-20
 * Time: 13:56
 **/
public class Member implements Serializable {

    @Override
    @Deprecated
    public String toString() {
        return super.toString();
    }
}
ackage com.bit.annotation;

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

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: wang
 * Date: 2019-05-20
 * Time: 14:09
 **/

@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.TYPE})
public @interface MyAnnotation{
    String name() default"无名";

    int age() default 18;

}    
package com.bit.annotation;


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

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: wang
 * Date: 2019-05-20
 * Time: 13:58
 **/
public class TestMember {

    public static void code1() {
        Class cls = Member.class;
        Annotation[] annotations = cls.getAnnotations();
        for(Annotation annotation:annotations){
            System.out.println(annotation);
        }
//        try{
//            Method method = cls.getMethod("toString");
//            Annotation[] annotations = method.getAnnotation();
//            for (Annotation annotation:annotations){
//                System.out.println(annotation);
//
//            }
//
    }

    public static void main(String[] args) {
        Class cls = Member.class;
        MyAnnotation myAnnotation = (MyAnnotation) cls.getDeclaredAnnotation(MyAnnotation.class);
        System.out.println(myAnnotation);
        int age = myAnnotation.age();
        String name = myAnnotation.name();
        System.out.println(name +" " + age);
    }
}    
    
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值