前面了解了注解的基本内容,这次来看一下自定义注解。

自定义注解其实很简单,直接上代码:

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";
}

根据上一篇对元注解的解释,我们知道:

  1. 这个注解可以用于方法
  2. JVM运行期间该注解都有效
  3. 该注解包含在 javadoc 中
  4. 该注解允许子类继承

下面看下通过注解我们能取到什么

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保留策略的注解信息。

最新文章

  1. 自己总结SVN必知点
  2. 场景3 Data Management
  3. ASP.NET MVC中实现多个按钮提交的几种方法
  4. UITableViewCell 自适应高度 ios8特性
  5. Redis - hash类型操作
  6. PHP htmlspecialchars() 函数
  7. Date Time Picker控件
  8. asp.net Listbox控件用法
  9. TCP/IP协议精华笔记
  10. Mybatis基本用法--中
  11. 在Ubuntu14.04下安装 labelImg (标数据用)
  12. JS中的特殊类别注意区分
  13. [Swift]LeetCode998. 最大二叉树 II | Maximum Binary Tree II
  14. MySQL 表字段操作
  15. wireshark捕获/显示过滤器表达式书写规律说明
  16. [原创]K8飞刀 新增Acunetix WVS 远程漏洞 反制黑客
  17. nginx配置二级域名
  18. JUC学习记录
  19. php页面的基本语法
  20. [翻译] 极具动感的 FRDLivelyButton

热门文章

  1. git提交忽略文件或文件夹
  2. python os.path 的使用
  3. Django(app的概念、ORM介绍及编码错误问题)
  4. hdoj1757 A Simple Math Problem(矩阵快速幂)
  5. spring-security(2)
  6. jvm高级特性(6)(线程的种类,调度,状态,安全程度,实现安全的方法,同步种类,锁优化,锁种类)
  7. iOS完全自学手册——[一]Ready?No!
  8. Centos下用yum命令按照jdk
  9. leetcode-64-最小路径和
  10. 第6章—渲染web视图—SpringMVC+Thymeleaf 处理表单提交