java之自定义注解第二篇
上篇文章内容我们分享一下了自定义注解的内容,这篇文章主要分享的内容就是关于如何获取自定义注解上面的内容。
好了,我们还是赶紧定义一个自定义注解的示例程序咯。更多教程请访问码农之家
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去获取属性上面的注解,最后就可以获取自定义注解上面的内容了,相信当你读完这句话的时候,你已经掌握了我告诉你的内容了,坏笑。
在这里有个很有意思的事情,每次当我写完这段话的时候,自己总会想到另外一个人嘲讽的意思,其实写文章帮助了自己很多,减少了很多缺点,也学会了很多技术之外的事情,其实古人的很多名言都确实很有意思,这也是自己有的时候特想说的,中文文字的魅力就在于它体现的意境,不可置否。
好了,讲解上面的自定义注解的内容,我们这篇文章就到这里结束了
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~