[关闭]
@nalan90 2018-07-06T12:08:44.000000Z 字数 7253 阅读 654

Annotation入门

Java开发


参考资料

注解的分类

自定义注解语法要求
  1. @Target({ElementType.METHOD, ElementType.TYPE})
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Inherited
  4. @Documented
  5. public @interface Description { // 使用@interface关键字定义注解
  6. String desc(); // 成员以无参无异常方式声明,返回类型就是参数的类型
  7. int age() default 18; // 可以用default为成员指定一个默认值
  8. }

注意点:


元注解(meta-annotation)

元注解即注解的注解,我们用元注解来定义其他注解。JDK5定义了4个标准meta-annotation类型,分别是@Target、@Retention、@Documented、@Inherited


实战一
  1. ## 定义Description注解
  2. package annotations;
  3. import java.lang.annotation.*;
  4. @Target(ElementType.TYPE)
  5. @Retention(RetentionPolicy.RUNTIME)
  6. @Documented
  7. public @interface Description {
  8. String value();
  9. }
  10. ## 定义Name注解
  11. package annotations;
  12. import java.lang.annotation.*;
  13. @Documented
  14. @Target(ElementType.METHOD)
  15. @Retention(RetentionPolicy.RUNTIME)
  16. public @interface Name {
  17. String originate();
  18. String community();
  19. }
  20. ## 实现类
  21. package com.demo;
  22. import annotations.Description;
  23. import annotations.Name;
  24. @Description("javaeye,做最棒的软件开发交流社区")
  25. public class JavaEyer {
  26. @Name(originate = "创始人:robbin", community = "javaEye")
  27. public String getName() {
  28. return null;
  29. }
  30. @Name(originate = "创始人:江南白衣", community = "springside")
  31. public String getName2() {
  32. return "借用两位的id一用";
  33. }
  34. }
  35. ## 测试用例
  36. package com.demo;
  37. import annotations.Description;
  38. import annotations.Name;
  39. import java.lang.annotation.Annotation;
  40. import java.lang.reflect.Method;
  41. import java.util.HashSet;
  42. import java.util.Set;
  43. public class TestAnnotation {
  44. public static void main(String[] args) throws Exception {
  45. Class test = Class.forName("com.demo.JavaEyer");
  46. Method[] methods = test.getMethods();
  47. boolean flag = test.isAnnotationPresent(Description.class);
  48. if (flag) {
  49. Description desc = (Description) test.getAnnotation(Description.class);
  50. System.out.println("描述:" + desc.value());
  51. System.out.println("----------------------");
  52. }
  53. Set<Method> set = new HashSet<>();
  54. for (int i = 0; i < methods.length; i++) {
  55. boolean otherFlag = methods[i].isAnnotationPresent(Name.class);
  56. if (otherFlag) {
  57. System.out.println(methods[i].getName());
  58. set.add(methods[i]);
  59. }
  60. }
  61. for (Method m: set) {
  62. Name name = m.getAnnotation(Name.class);
  63. System.out.println(name.originate() + "--->" + name.community());
  64. }
  65. for (Method m: set) {
  66. Annotation[] anns = m.getAnnotations();
  67. for (Annotation ann: anns) {
  68. if(ann instanceof Name) {
  69. Name name = (Name) ann;
  70. System.out.println(name.originate() + "--->" + name.community());
  71. }
  72. }
  73. }
  74. }
  75. }
  76. ##执行结果:
  77. 描述:javaeye,做最棒的软件开发交流社区
  78. ----------------------
  79. getName
  80. getName2
  81. 创始人:robbin--->javaEye
  82. 创始人:江南白衣--->springside
  83. 创始人:robbin--->javaEye
  84. 创始人:江南白衣--->springside

实例二
  1. ## 定义Table注解
  2. package com.annotation.test;
  3. import java.lang.annotation.ElementType;
  4. import java.lang.annotation.Retention;
  5. import java.lang.annotation.RetentionPolicy;
  6. import java.lang.annotation.Target;
  7. @Target(ElementType.TYPE)
  8. @Retention(RetentionPolicy.RUNTIME)
  9. public @interface Table {
  10. String value();
  11. }
  12. ## 定义Column注解
  13. package com.annotation.test;
  14. import java.lang.annotation.ElementType;
  15. import java.lang.annotation.Retention;
  16. import java.lang.annotation.RetentionPolicy;
  17. import java.lang.annotation.Target;
  18. @Target(ElementType.FIELD)
  19. @Retention(RetentionPolicy.RUNTIME)
  20. public @interface Column {
  21. String value();
  22. }
  23. ## Invest Bean
  24. package com.annotation.test;
  25. @Table("core_invest")
  26. public class Invest {
  27. @Column("id")
  28. private int id;
  29. @Column("user_id")
  30. private int userId;
  31. @Column("cash")
  32. private double cash;
  33. @Column("project_id")
  34. private int projectId;
  35. public int getId() {
  36. return id;
  37. }
  38. public void setId(int id) {
  39. this.id = id;
  40. }
  41. public int getUserId() {
  42. return userId;
  43. }
  44. public void setUserId(int userId) {
  45. this.userId = userId;
  46. }
  47. public double getCash() {
  48. return cash;
  49. }
  50. public void setCash(double cash) {
  51. this.cash = cash;
  52. }
  53. public int getProjectId() {
  54. return projectId;
  55. }
  56. public void setProjectId(int projectId) {
  57. this.projectId = projectId;
  58. }
  59. }
  60. ## User Bean
  61. package com.annotation.test;
  62. @Table("core_user")
  63. public class User {
  64. @Column("id")
  65. private int id;
  66. @Column("phone")
  67. private String phone;
  68. @Column("real_name")
  69. private String realName;
  70. @Column("email")
  71. private String email;
  72. @Column("balance")
  73. private double balance;
  74. public int getId() {
  75. return id;
  76. }
  77. public void setId(int id) {
  78. this.id = id;
  79. }
  80. public String getPhone() {
  81. return phone;
  82. }
  83. public void setPhone(String phone) {
  84. this.phone = phone;
  85. }
  86. public String getRealName() {
  87. return realName;
  88. }
  89. public void setRealName(String realName) {
  90. this.realName = realName;
  91. }
  92. public String getEmail() {
  93. return email;
  94. }
  95. public void setEmail(String email) {
  96. this.email = email;
  97. }
  98. public double getBalance() {
  99. return balance;
  100. }
  101. public void setBalance(double balance) {
  102. this.balance = balance;
  103. }
  104. }
  105. ## 测试类
  106. package com.annotation.test;
  107. import java.lang.reflect.Field;
  108. import java.lang.reflect.Method;
  109. public class Test {
  110. public static void main(String[] args){
  111. testUserAnnotations();
  112. testInvestAnnotations();
  113. }
  114. public static void testInvestAnnotations() {
  115. System.out.println("--------Test Invest Annotations---------");
  116. String sql = null;
  117. Invest invest = null;
  118. try {
  119. invest = new Invest();
  120. invest.setId(10);
  121. sql = query(invest);
  122. System.out.println(sql);
  123. invest = new Invest();
  124. invest.setUserId(82692);
  125. sql = query(invest);
  126. System.out.println(sql);
  127. invest = new Invest();
  128. invest.setUserId(82692);
  129. invest.setProjectId(1000);
  130. sql = query(invest);
  131. System.out.println(sql);
  132. } catch (Exception e) {
  133. e.printStackTrace();
  134. }
  135. }
  136. public static void testUserAnnotations() {
  137. System.out.println("--------Test User Annotations---------");
  138. String sql = null;
  139. User user = null;
  140. try {
  141. user = new User();
  142. user.setId(10);
  143. sql = query(user);
  144. System.out.println(sql);
  145. user = new User();
  146. user.setPhone("18510258037");
  147. sql = query(user);
  148. System.out.println(sql);
  149. user = new User();
  150. user.setPhone("18510258037");
  151. user.setEmail("admin@admin.com");
  152. sql = query(user);
  153. System.out.println(sql);
  154. } catch (Exception e) {
  155. e.printStackTrace();
  156. }
  157. }
  158. private static String query(Object object) throws Exception{
  159. StringBuilder sb = new StringBuilder();
  160. Class c = object.getClass();
  161. boolean flag = c.isAnnotationPresent(Table.class);
  162. if (!flag) {
  163. return null;
  164. }
  165. Table table = (Table) c.getAnnotation(Table.class);
  166. String tableName = table.value();
  167. sb.append("select * from ").append(tableName).append(" where 1=1");
  168. //获取类中定义的所有属性
  169. Field[] fields = c.getDeclaredFields();
  170. for(Field field: fields) {
  171. //获取属性名称
  172. String fieldName = field.getName();
  173. flag = field.isAnnotationPresent(Column.class);
  174. if (!flag) {
  175. continue;
  176. }
  177. //拼装getter方法名
  178. String getMethodName = "get" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
  179. //获取getter方法实体
  180. Method getMethod = c.getMethod(getMethodName);
  181. //获取getter方法
  182. Object result = getMethod.invoke(object);
  183. if (result == null) {
  184. continue;
  185. }
  186. if (result instanceof Integer && (Integer)result == 0) {
  187. continue;
  188. }
  189. if (result instanceof Double && (Double)result == 0.0) {
  190. continue;
  191. }
  192. String columnName = field.getAnnotation(Column.class).value();
  193. sb.append(" and ").append(columnName).append("=");
  194. if (result instanceof String) {
  195. sb.append("'").append(result).append("'");
  196. }
  197. if (result instanceof Integer) {
  198. sb.append(result);
  199. }
  200. }
  201. return sb.toString();
  202. }
  203. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注