Java注解:

注解的实现:

package JavaCore;

import java.lang.annotation.*;

//@MyAnnotation 报错
public class Innocation {
    public static void main(String[] args) {
        
    }
    @MyAnnotation(name = "人")
    public void test(){
        
    }
    
}

//元注解
@Target(value = ElementType.METHOD)//Target表示能够作用在哪里
@Retention(value = RetentionPolicy.RUNTIME) //运行时有效
@Documented       //是否将注解生成在JAVAdoc中
@Inherited        //子类可以继承父类的注解    
@interface MyAnnotation{
    //注解的参数:参数类型+参数名();
    String name() default "";
    int id() default -1;
    String[] str() default {"s1","s2"};

}

反射操作注解;

package JavaCore;

import java.lang.annotation.*;
import java.lang.reflect.Field;


public class Innocation {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        Class stu = Class.forName("JavaCore.Student");
        //获得类上的注解
        MyAnnotation annotation = (MyAnnotation) stu.getAnnotation(MyAnnotation.class);
        System.out.println(annotation.value());
        //我是类上的注解

        //获得成员变量上的注解
        Field name = stu.getDeclaredField("name");
        MyName myName = name.getAnnotation(MyName.class);
        System.out.println(myName.name());
        //小明

    }

}
@MyAnnotation("我是类上的注解")
class Student{
    @MyName(name = "小明")
    private String name;

    public Student() {
    }
    public Student(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

@Target(value = {ElementType.METHOD,ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
@Inherited
@interface MyAnnotation{
    String value();
}

@Target(value = {ElementType.METHOD,ElementType.TYPE,ElementType.FIELD})
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
@Inherited
@interface MyName{
    String name();
}

面试题:https://blog.csdn.net/qq_37939251/article/details/83215703?utm_term=Java%E6%B3%A8%E8%A7%A3%E9%9D%A2%E8%AF%95%E9%A2%98&utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~all~sobaiduweb~default-1-83215703&spm=3001.4430

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值