java Annotation注解(一)基本用法练习

业精于勤荒于嬉,写文章练习表达能力,写代码练习基本工。

练习目标:

掌握注解的基本用法,自定义注解,使用注解,读取注解(使用反射)。

学习内容:

  1. 自定义注解Myannotation,定义属性(姓名,年龄),提供默认值。
  2. 给某一个个对象字段使用注解,给想要的初始值。
  3. 使用反射,获取注解的属性值,并给对应字段赋值,完成对象初始化。

简单点说,其实就是利用注解,自动完成创建对象,初始化赋值的操作。

代码清单:

Test

public class Test {

	//需求就是按照注解的值,来完成person的初始化并赋值。
    @Myannotation(name = "larry",age = 12)
    private static Person person;//
    //public static Person person;//一个用private,一个用public,占个坑,后面说明。

    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        System.out.println("hello my annotation !!! ");
        //反射读取注解,初始化,赋值过程。
        PersonUtils.injectValue(Test.class);
        //验证下是否正常
        System.out.println(person.age);
        System.out.println(person.name);
    }

}

hello my annotation !!!
12
larry

Myannotation

@Retention(RetentionPolicy.RUNTIME)//作用于一定要是RUNTIME,因为是运行时使用的反射来获取的。
@Target(ElementType.FIELD)
public @interface Myannotation {
    int value() default 100;
    String name() default "";
    int age() default 0;
}

Person

public class Person {

    int age;
    String name;

}

PersonUtils

public class PersonUtils {

    public static  void injectValue(Class clazz) throws IllegalAccessException, InstantiationException {
        Field[] fields = clazz.getDeclaredFields();//对应Test.java中persion的修饰符
        for (Field field:fields){
            if(field.isAnnotationPresent(Myannotation.class)){
                Myannotation myannotation = field.getDeclaredAnnotation(Myannotation.class);
                int age = myannotation.age();
                String name = myannotation.name();
                Person person = Person.class.newInstance();
                person.age = age;
                person.name = name;
                field.setAccessible(true);
                field.set(null,person);
            }
        }
    }

}

要点(在这几个地方出错了,记录下)

  1. 使用反射获取成员变量时,getDeclaredFields和getFields的区别。

getFields():获得某个类的所有的公共(public)的字段,包括父类中的字段。
getDeclaredFields():获得某个类的所有声明的字段,即包括public、private和proteced,但是不包括父类的申明字段。

  1. 注解的作用域,如果想运行时,通过反射获取,必须使用RUNTIME级别。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值