java 注解(二)

如何自定义注解:参照@SuppressWarnings定义
一.注解声明为:@interface
二.内部指定成员 通常用value表示
三.可以指定成员的默认值 使用default表示
四.如果自定义注解没有成员 表明是一个标识作用
如果注解有成员 在使用注解时 需要指明成员的值

如果注解有成员 在使用注解时 需要指明成员的值
自定义注解必须配上注解的信息处理流程才有意义
自定义注解通过都会指明两个元注解:Retention target
jdk提供的四种元注解:对现有的注解进行解释说明
Retention:指定所修饰的Annotation的生命周期:SOURCE\CLASS\RUNTIME
只有声明为RUNTIME生命周期的注解 才能通过反射获取

Target:用于指定被修饰的Annotation能用于修饰哪些程序元素

Doctmented:表示所修饰的注解在被javadoc解析时 保留下来

inherited:被它修饰的Annotation具有继承性
通过反射获取注解信息——反射

import org.junit.Test;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedArrayType;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Date;

public class AnnotationTest {
    public static void main(String[] args) {
        Person p = new Student();
        p.walk();

        Date date = new Date(2020,10,11);
        System.out.println(date);

        @SuppressWarnings("unused")
        int num = 10;

        @SuppressWarnings({"unused","rawtypes"})
        ArrayList list = new ArrayList();
    }
    @Test
    public void testGetAnnotation(){
        Class clazz = Student.class;
        Annotation[] annotations = clazz.getAnnotations();
        for (int i = 0;i < annotations.length; i++){
            System.out.println(annotations[i]);
        }
    }
}
@MyAnnotation(value = "hello")
class Person{
    private String name;
    private int age;

    public Person() {
    }
@MyAnnotation
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @MyAnnotation
    public void walk(){
        System.out.println("人走路");
    }
    public void eat(){
        System.out.println("人吃饭");
    }
}
interface Info{
    void show();
}
class Student extends Person {
    @Override
    public void walk() {
        System.out.println("学生走路");
    }
}
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;

@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE})
public @interface MyAnnotation {
    String value() default "hello";
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值