Java注解(二)
2024-10-01 11:59:39
前面了解了注解的基本内容,这次来看一下自定义注解。
自定义注解其实很简单,直接上代码:
import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy; @Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
/*
* 定义注解 Test
* 注解中含有两个元素 id 和 description
* description 元素 有默认值 "hello anntation"
*/
public @interface Test {
public int id();
public String description() default "hello annotation";
}
根据上一篇对元注解的解释,我们知道:
- 这个注解可以用于方法
- JVM运行期间该注解都有效
- 该注解包含在 javadoc 中
- 该注解允许子类继承
下面看下通过注解我们能取到什么
public class TestMain {
/*
* 被注解的三个方法
*/
@Test(id = 1, description = "hello methodA")
public void methodA() {
} @Test(id = 2)
public void methodB() {
} @Test(id = 3, description = "last method")
public void methodC() {
} /*
* 解析注解,将类被注解方法 的信息打印出来
*/
public static void main(String[] args) {
Method[] methods = TestMain.class.getDeclaredMethods();
for (Method method : methods) {
/*
* 判断方法中是否有指定注解类型的注解
*/
boolean hasAnnotation = method.isAnnotationPresent(Test.class);
if (hasAnnotation) {
/*
* 根据注解类型返回方法的指定类型注解
*/
Test annotation = method.getAnnotation(Test.class);
System.out.println("Test( method = " + method.getName() + " , id = " + annotation.id()
+ " , description = " + annotation.description() + " )");
}
}
}
}
上面的Demo打印的结果如下:
Test( method = methodA , id = 1 , description = hello methodA )
Test( method = methodB , id = 2 , description = hello annotation )
Test( method = methodC , id = 3 , description = last method )
上例其实也说明了,我们一般通过反射来取RUNTIME保留策略的注解信息。
最新文章
- 自己总结SVN必知点
- 场景3 Data Management
- ASP.NET MVC中实现多个按钮提交的几种方法
- UITableViewCell 自适应高度 ios8特性
- Redis - hash类型操作
- PHP htmlspecialchars() 函数
- Date Time Picker控件
- asp.net Listbox控件用法
- TCP/IP协议精华笔记
- Mybatis基本用法--中
- 在Ubuntu14.04下安装 labelImg (标数据用)
- JS中的特殊类别注意区分
- [Swift]LeetCode998. 最大二叉树 II | Maximum Binary Tree II
- MySQL 表字段操作
- wireshark捕获/显示过滤器表达式书写规律说明
- [原创]K8飞刀 新增Acunetix WVS 远程漏洞 反制黑客
- nginx配置二级域名
- JUC学习记录
- php页面的基本语法
- [翻译] 极具动感的 FRDLivelyButton
热门文章
- git提交忽略文件或文件夹
- python os.path 的使用
- Django(app的概念、ORM介绍及编码错误问题)
- hdoj1757 A Simple Math Problem(矩阵快速幂)
- spring-security(2)
- jvm高级特性(6)(线程的种类,调度,状态,安全程度,实现安全的方法,同步种类,锁优化,锁种类)
- iOS完全自学手册——[一]Ready?No!
- Centos下用yum命令按照jdk
- leetcode-64-最小路径和
- 第6章—渲染web视图—SpringMVC+Thymeleaf 处理表单提交