@nalan90
2018-07-06T04:08:44.000000Z
字数 7253
阅读 806
Java开发
按照运行机制分
按来源来分
@Target({ElementType.METHOD, ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Inherited@Documentedpublic @interface Description { // 使用@interface关键字定义注解String desc(); // 成员以无参无异常方式声明,返回类型就是参数的类型int age() default 18; // 可以用default为成员指定一个默认值}
注意点:
元注解即注解的注解,我们用元注解来定义其他注解。JDK5定义了4个标准meta-annotation类型,分别是@Target、@Retention、@Documented、@Inherited
@Target
说明注解所修饰的对象范围,指注解可以用在什么地方。
@Retention
即上文提到的注解在什么时候起作用。
@Documented
用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化。它是一个标记注解,没有成员。
@Inherited
它是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。
## 定义Description注解package annotations;import java.lang.annotation.*;@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface Description {String value();}## 定义Name注解package annotations;import java.lang.annotation.*;@Documented@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface Name {String originate();String community();}## 实现类package com.demo;import annotations.Description;import annotations.Name;@Description("javaeye,做最棒的软件开发交流社区")public class JavaEyer {@Name(originate = "创始人:robbin", community = "javaEye")public String getName() {return null;}@Name(originate = "创始人:江南白衣", community = "springside")public String getName2() {return "借用两位的id一用";}}## 测试用例package com.demo;import annotations.Description;import annotations.Name;import java.lang.annotation.Annotation;import java.lang.reflect.Method;import java.util.HashSet;import java.util.Set;public class TestAnnotation {public static void main(String[] args) throws Exception {Class test = Class.forName("com.demo.JavaEyer");Method[] methods = test.getMethods();boolean flag = test.isAnnotationPresent(Description.class);if (flag) {Description desc = (Description) test.getAnnotation(Description.class);System.out.println("描述:" + desc.value());System.out.println("----------------------");}Set<Method> set = new HashSet<>();for (int i = 0; i < methods.length; i++) {boolean otherFlag = methods[i].isAnnotationPresent(Name.class);if (otherFlag) {System.out.println(methods[i].getName());set.add(methods[i]);}}for (Method m: set) {Name name = m.getAnnotation(Name.class);System.out.println(name.originate() + "--->" + name.community());}for (Method m: set) {Annotation[] anns = m.getAnnotations();for (Annotation ann: anns) {if(ann instanceof Name) {Name name = (Name) ann;System.out.println(name.originate() + "--->" + name.community());}}}}}##执行结果:描述:javaeye,做最棒的软件开发交流社区----------------------getNamegetName2创始人:robbin--->javaEye创始人:江南白衣--->springside创始人:robbin--->javaEye创始人:江南白衣--->springside
## 定义Table注解package com.annotation.test;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface Table {String value();}## 定义Column注解package com.annotation.test;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface Column {String value();}## Invest Beanpackage com.annotation.test;@Table("core_invest")public class Invest {@Column("id")private int id;@Column("user_id")private int userId;@Column("cash")private double cash;@Column("project_id")private int projectId;public int getId() {return id;}public void setId(int id) {this.id = id;}public int getUserId() {return userId;}public void setUserId(int userId) {this.userId = userId;}public double getCash() {return cash;}public void setCash(double cash) {this.cash = cash;}public int getProjectId() {return projectId;}public void setProjectId(int projectId) {this.projectId = projectId;}}## User Beanpackage com.annotation.test;@Table("core_user")public class User {@Column("id")private int id;@Column("phone")private String phone;@Column("real_name")private String realName;@Column("email")private String email;@Column("balance")private double balance;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}public String getRealName() {return realName;}public void setRealName(String realName) {this.realName = realName;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public double getBalance() {return balance;}public void setBalance(double balance) {this.balance = balance;}}## 测试类package com.annotation.test;import java.lang.reflect.Field;import java.lang.reflect.Method;public class Test {public static void main(String[] args){testUserAnnotations();testInvestAnnotations();}public static void testInvestAnnotations() {System.out.println("--------Test Invest Annotations---------");String sql = null;Invest invest = null;try {invest = new Invest();invest.setId(10);sql = query(invest);System.out.println(sql);invest = new Invest();invest.setUserId(82692);sql = query(invest);System.out.println(sql);invest = new Invest();invest.setUserId(82692);invest.setProjectId(1000);sql = query(invest);System.out.println(sql);} catch (Exception e) {e.printStackTrace();}}public static void testUserAnnotations() {System.out.println("--------Test User Annotations---------");String sql = null;User user = null;try {user = new User();user.setId(10);sql = query(user);System.out.println(sql);user = new User();user.setPhone("18510258037");sql = query(user);System.out.println(sql);user = new User();user.setPhone("18510258037");user.setEmail("admin@admin.com");sql = query(user);System.out.println(sql);} catch (Exception e) {e.printStackTrace();}}private static String query(Object object) throws Exception{StringBuilder sb = new StringBuilder();Class c = object.getClass();boolean flag = c.isAnnotationPresent(Table.class);if (!flag) {return null;}Table table = (Table) c.getAnnotation(Table.class);String tableName = table.value();sb.append("select * from ").append(tableName).append(" where 1=1");//获取类中定义的所有属性Field[] fields = c.getDeclaredFields();for(Field field: fields) {//获取属性名称String fieldName = field.getName();flag = field.isAnnotationPresent(Column.class);if (!flag) {continue;}//拼装getter方法名String getMethodName = "get" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);//获取getter方法实体Method getMethod = c.getMethod(getMethodName);//获取getter方法Object result = getMethod.invoke(object);if (result == null) {continue;}if (result instanceof Integer && (Integer)result == 0) {continue;}if (result instanceof Double && (Double)result == 0.0) {continue;}String columnName = field.getAnnotation(Column.class).value();sb.append(" and ").append(columnName).append("=");if (result instanceof String) {sb.append("'").append(result).append("'");}if (result instanceof Integer) {sb.append(result);}}return sb.toString();}}