自定义Annotation

拼搏现实的明天。 2022-08-26 01:21 215阅读 0赞
  1. package com.test.javaSe01;
  2. import java.lang.annotation.Retention;
  3. import java.lang.annotation.RetentionPolicy;
  4. import java.lang.reflect.Method;
  5. @Retention(value = RetentionPolicy.RUNTIME)
  6. // 此句必须有//\u6B64\u53E5\u5FC5\u987B\u6709
  7. @interface MySelfAnnotation {
  8. public int age() default 23;
  9. public String name() default "ctl";
  10. }
  11. @MySelfAnnotation(age = 100, name = "蔡腾林")
  12. class Person {
  13. int age;
  14. String name;
  15. public int getAge() {
  16. return age;
  17. }
  18. public void setAge(int age) {
  19. this.age = age;
  20. }
  21. public String getName() {
  22. return name;
  23. }
  24. public void setName(String name) {
  25. this.name = name;
  26. }
  27. public int hashCode() {
  28. return super.hashCode();
  29. }
  30. @MySelfAnnotation(age = 230, name = "ctllin")
  31. public String toString() {
  32. return this.name + " " + this.age;
  33. }
  34. @MySelfAnnotation
  35. public void print() {
  36. }
  37. }
  38. /**
  39. *
  40. * @author Administrator
  41. * @deprecated 获取自定义Annotation中的值 自定义的Annotation分别定义到类和方法上
  42. */
  43. public class SelfAnnotationTestDemo {
  44. public static void main(String[] args) {
  45. SelfAnnotationTestDemo sa = new SelfAnnotationTestDemo();
  46. Class<?> c = null;
  47. try {
  48. c = Class.forName("com.test.javaSe01.Person");
  49. if (c.isAnnotationPresent(MySelfAnnotation.class)) {
  50. MySelfAnnotation ma = c.getAnnotation(MySelfAnnotation.class);
  51. System.out.println(ma.name() + " " + ma.age());
  52. }
  53. } catch (ClassNotFoundException e) {
  54. System.err.println("com.test.javaSe01.Person没有找到");
  55. e.printStackTrace();
  56. }
  57. Method method = null, method1 = null;
  58. try {
  59. method = c.getMethod("toString");
  60. System.out.println(method);
  61. method1 = c.getMethod("print");
  62. System.out.println(method1);
  63. } catch (SecurityException e) {
  64. e.printStackTrace();
  65. } catch (NoSuchMethodException e) {
  66. e.printStackTrace();
  67. }
  68. if (method.isAnnotationPresent(MySelfAnnotation.class)) {
  69. MySelfAnnotation myAnnotation = method
  70. .getAnnotation(MySelfAnnotation.class);
  71. int age = myAnnotation.age();
  72. String name = myAnnotation.name();
  73. System.out.println(name + " " + age);
  74. }
  75. if (method1.isAnnotationPresent(MySelfAnnotation.class)) {
  76. MySelfAnnotation myAnnotation = method1
  77. .getAnnotation(MySelfAnnotation.class);
  78. int age = myAnnotation.age();
  79. String name = myAnnotation.name();
  80. System.out.println(name + " " + age);
  81. }
  82. }
  83. }

发表评论

表情:
评论列表 (有 0 条评论,215人围观)

还没有评论,来说两句吧...

相关阅读

    相关 定义注解 annotation 总结

    要深入学习注解,我们就必须能定义自己的注解,并使用注解,在定义自己的注解之前,我们就必须要了解Java为我们提供的元注解和相关定义注解的语法。所以这篇文章我会首先和大家介绍一下