java之自定义注解第二篇
- 2019 年 11 月 26 日
- 筆記
好了,我们还是赶紧定义一个自定义注解的示例程序咯。
package com.wpw.springboot; import java.lang.annotation.*; @Documented @Inherited @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface ContentAnnotation { String value () default "111"; }
上面注解的内容就是说你没有给value赋值,就使用默认值111。
我们看下我们自定义注解使用的类,主要是用来做简单的示例程序的,所以写法也比较简单一些。
package com.wpw.springboot; public class Student { @ContentAnnotation(value = "backcoder") private String name; @ContentAnnotation private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
接下来,我们写个示例程序去获取自定义注解里面的内容。
package com.wpw.springboot; import java.lang.reflect.Field; public class MyTest2 { public static void main(String[] args) throws NoSuchFieldException { Class<Student> studentClass = Student.class; Field studentClassDeclaredField = studentClass.getDeclaredField("name"); boolean flag = studentClassDeclaredField.isAnnotationPresent(ContentAnnotation.class); if (flag){ System.out.println("属性name是被注解进行修饰的"); } ContentAnnotation fieldAnnotation = studentClassDeclaredField.getAnnotation(ContentAnnotation.class); String value = fieldAnnotation.value(); System.out.println(value); Field studentClassDeclaredField1 = studentClass.getDeclaredField("age"); ContentAnnotation field1Annotation = studentClassDeclaredField1.getAnnotation(ContentAnnotation.class); String value1 = field1Annotation.value(); System.out.println(value1); } }
首先,我们获取自己定义类的Class对象,然后根据指定的属性名去获取对应的Field值,然后就根据Field去获取属性上面的注解,最后就可以获取自定义注解上面的内容了,相信当你读完这句话的时候,你已经掌握了我告诉你的内容了,坏笑。
在这里有个很有意思的事情,每次当我写完这段话的时候,自己总会想到另外一个人嘲讽的意思,其实写文章帮助了自己很多,减少了很多缺点,也学会了很多技术之外的事情,其实古人的很多名言都确实很有意思,这也是自己有的时候特想说的,中文文字的魅力就在于它体现的意境,不可置否。
好了,讲解上面的自定义注解的内容,我们这篇文章就到这里结束了