Java注解-自定义注解实例

在Java中注解随处可见,学习Java注解,知道其原理,可以读懂很多开源框架,如Spring,Mybatis等,还可以自定义注解实现更高级的功能。 

 

一、常见的Java注解

 Jdk自带的注解:@Override,@SuppressWarnings,@Deprecated(方法过时)

 第三方框架注解:Spring,Mybatis等

 

二、注解的分类

1.按运行机制分

 源码注解     源码存在,class文件不存在

 编译时注解  源码,class文件存在

 运行时注解  spring @antuAire

2.按来源分

 Jdk自带的注解

 第三方注解

 自定义注解

3.元注解

 给注解用的注解

 

三、注解语法

1.声明public @interface

2.成员以无参无异常方式声明

3.可以用default为成员指定一个默认值

    int age() default 18;

4.成员的返回值类型是有限制的,合法的有基本数据类型,String,Class,Annotation,Enurmeration

5.如果注解只有一个成员,则成员名必须为value(),在使用时可以忽略成员名和赋值号(=)

6.注解类可以没有成员,没有成员的注解为标识注解

 

元注解

作用于注解上的注解,如@Target,@Retention,@Inherited,@Documented

Java代码   收藏代码
  1. package com.yuwl.ann;  
  2.   
  3. import java.lang.annotation.Documented;  
  4. import java.lang.annotation.ElementType;  
  5. import java.lang.annotation.Inherited;  
  6. import java.lang.annotation.Retention;  
  7. import java.lang.annotation.RetentionPolicy;  
  8. import java.lang.annotation.Target;  
  9.   
  10. /** 
  11.  * 自定义注解 
  12.  * @author Yuwl 
  13.  */  
  14. @Target({ElementType.METHOD,ElementType.TYPE})  
  15. @Retention(RetentionPolicy.RUNTIME)  
  16. @Inherited  
  17. @Documented  
  18. public @interface Description {  
  19.       
  20.     String value();  
  21.   
  22. }  

 Target注解:注解的作用域,用在哪个地方,包含Java的所有元素:

 CONSTRUCTOR 构造方法

 FiELD 字段

 LOCAL_VERIABLE 局部变量

 METHOD 方法

 PACKAGE 包

 TYPE 类接口

 

Retention注解:生命周期,包含:

SOURCE 源码

CLASS 编译

RUNNTIME 运行时

 

Inheriter注解:标识性元注解,允许子类继承,但只适用于类的继承,不能用于接口继承,而且只会继承类的注解,不会继承方法的

 

 

Documented注解:生成javadoc时会包含注解

 

注解的使用:

@注解名(成员名1=成员值1,成员名2=成员值2)

 

四、自定义注解

1.自定义注解

Java代码   收藏代码
  1. package com.yuwl.ann;  
  2.   
  3. import java.lang.annotation.Documented;  
  4. import java.lang.annotation.ElementType;  
  5. import java.lang.annotation.Inherited;  
  6. import java.lang.annotation.Retention;  
  7. import java.lang.annotation.RetentionPolicy;  
  8. import java.lang.annotation.Target;  
  9.   
  10. /** 
  11.  * 自定义注解 
  12.  * @author Yuwl 
  13.  */  
  14. @Target({ElementType.METHOD,ElementType.TYPE})  
  15. @Retention(RetentionPolicy.RUNTIME)  
  16. @Inherited  
  17. @Documented  
  18. public @interface Description {  
  19.       
  20.     String value();  
  21.   
  22. }  

2.注解的使用

Java代码   收藏代码
  1. package com.yuwl.ann;  
  2.   
  3. /** 
  4.  * 自定义注解的使用 
  5.  * @author Yuwl 
  6.  */  
  7. @Description("I am class annotation")  
  8. public class UseAnnotation {  
  9.       
  10.     @Description("I am method annotation")  
  11.     public void hello(){  
  12.           
  13.     }  
  14.   
  15. }  

3.注解的解析

Java代码   收藏代码
  1. package com.yuwl.ann;  
  2.   
  3. import java.lang.annotation.Annotation;  
  4. import java.lang.reflect.Method;  
  5. /** 
  6.  * 解析注解 
  7.  * @author Yuwl 
  8.  */  
  9. public class ParseAnnotation {  
  10.   
  11.     public static void main(String[] args) {  
  12.         try {  
  13.             //1.使用类加载器加载类  
  14.             Class c = Class.forName("com.yuwl.ann.UseAnnotation");  
  15.             //2.找到类上的注解  
  16.             boolean exist = c.isAnnotationPresent(Description.class);  
  17.             if(exist){  
  18.                 //3.拿到注解实例  
  19.                 Description d = (Description)c.getAnnotation(Description.class);  
  20.                 System.out.println(d.value());  
  21.             }  
  22.               
  23.             //4.找到方法上的注解  
  24.             Method[] ms = c.getMethods();  
  25.             for(Method m : ms){  
  26.                 if(m.isAnnotationPresent(Description.class)){  
  27.                     Description d = (Description)m.getAnnotation(Description.class);  
  28.                     System.out.println(d.value());  
  29.                 }  
  30.             }  
  31.             //5.方法注解的另一种解析方式  
  32.             for(Method m : ms){  
  33.                 Annotation[] ans = m.getAnnotations();  
  34.                 for(Annotation an : ans){  
  35.                     Description d = (Description)an;  
  36.                     System.out.println(d.value());  
  37.                 }  
  38.             }  
  39.         } catch (Exception e) {  
  40.             e.printStackTrace();  
  41.         }  
  42.     }  
  43.   
  44. }  

 注解的解析主要用到Java的反射。

 

五、模拟实体到数据库表字段的映射

1.自定义表,字段注解

Java代码   收藏代码
  1. package com.yuwl.ann.dao;  
  2.   
  3. import java.lang.annotation.Documented;  
  4. import java.lang.annotation.ElementType;  
  5. import java.lang.annotation.Inherited;  
  6. import java.lang.annotation.Retention;  
  7. import java.lang.annotation.RetentionPolicy;  
  8. import java.lang.annotation.Target;  
  9. /** 
  10.  * 表自定义注解 
  11.  * @author Yuwl 
  12.  */  
  13. @Target({ElementType.TYPE})  
  14. @Retention(RetentionPolicy.RUNTIME)  
  15. @Inherited  
  16. @Documented  
  17. public @interface Table {  
  18.   
  19.     String value();  
  20. }  

 

Java代码   收藏代码
  1. package com.yuwl.ann.dao;  
  2.   
  3. import java.lang.annotation.Documented;  
  4. import java.lang.annotation.ElementType;  
  5. import java.lang.annotation.Inherited;  
  6. import java.lang.annotation.Retention;  
  7. import java.lang.annotation.RetentionPolicy;  
  8. import java.lang.annotation.Target;  
  9. /** 
  10.  * 字段自定义注解 
  11.  * @author Yuwl 
  12.  */  
  13. @Target({ElementType.FIELD})  
  14. @Retention(RetentionPolicy.RUNTIME)  
  15. @Inherited  
  16. @Documented  
  17. public @interface Column {  
  18.   
  19.     String value();  
  20. }  

 2.实体使用注解

Java代码   收藏代码
  1. package com.yuwl.ann.dao;  
  2. /** 
  3.  * 用户实体使用注解 
  4.  * @author Yuwl 
  5.  */  
  6. @Table("user")  
  7. public class User {  
  8.       
  9.     @Column("id")  
  10.     private int id;  
  11.       
  12.     @Column("userName")  
  13.     private String userName;  
  14.       
  15.     @Column("sex")  
  16.     private int sex;  
  17.       
  18.     @Column("mobile")  
  19.     private String mobile;  
  20.   
  21.     public int getId() {  
  22.         return id;  
  23.     }  
  24.   
  25.     public void setId(int id) {  
  26.         this.id = id;  
  27.     }  
  28.   
  29.     public String getUserName() {  
  30.         return userName;  
  31.     }  
  32.   
  33.     public void setUserName(String userName) {  
  34.         this.userName = userName;  
  35.     }  
  36.   
  37.     public int getSex() {  
  38.         return sex;  
  39.     }  
  40.   
  41.     public void setSex(int sex) {  
  42.         this.sex = sex;  
  43.     }  
  44.   
  45.   
  46.     public String getMobile() {  
  47.         return mobile;  
  48.     }  
  49.   
  50.     public void setMobile(String mobile) {  
  51.         this.mobile = mobile;  
  52.     }  
  53.       
  54.   
  55. }  

 3.测试

Java代码   收藏代码
  1. package com.yuwl.ann.dao;  
  2.   
  3. import java.lang.reflect.Field;  
  4. import java.lang.reflect.Method;  
  5. /** 
  6.  * 模拟实体到数据库表字段的测试 
  7.  * @author Yuwl 
  8.  */  
  9. public class Test {  
  10.   
  11.     public static void main(String[] args) {  
  12.         User u = new User();  
  13.         u.setUserName("张三");  
  14.         u.setSex(1);  
  15.         System.out.println(parseUser(u));  
  16.     }  
  17.       
  18.     public static String parseUser(User u){  
  19.         StringBuffer sb = new StringBuffer();  
  20.         sb.append("select * from ");  
  21.         try {  
  22.             //1.获取表名  
  23.             Class c = Class.forName("com.yuwl.ann.dao.User");  
  24.             if(c.isAnnotationPresent(Table.class)){  
  25.                 Table t = (Table)c.getAnnotation(Table.class);  
  26.                 String tableName = t.value();  
  27.                 sb.append(tableName);  
  28.             }  
  29.             sb.append(" where 1=1");  
  30.             //2.获取字段名与值  
  31.             Field[] fs = c.getDeclaredFields();  
  32.             for(Field f : fs){  
  33.                 //2.1字段名  
  34.                 String column = "";  
  35.                 if(f.isAnnotationPresent(Column.class)){  
  36.                     Column fld = (Column)f.getAnnotation(Column.class);  
  37.                     column = fld.value();  
  38.                 }  
  39.                 //2.2字段值  
  40.                 String fieldName = f.getName();  
  41.                 String getMethod = "get"+fieldName.substring(01).toUpperCase()+fieldName.substring(1);  
  42.                 Method method = c.getMethod(getMethod);  
  43.                 Object fieldValue = method.invoke(u);  
  44.                 if(fieldValue instanceof Integer && (Integer)fieldValue == 0){  
  45.                     continue;  
  46.                 }  
  47.                 if(fieldValue != null){  
  48.                     sb.append(" and ").append(column).append("=");  
  49.                     if(fieldValue instanceof String){  
  50.                         sb.append("'").append(fieldValue).append("'");  
  51.                     }else{  
  52.                         sb.append(fieldValue);  
  53.                     }  
  54.                       
  55.                 }  
  56.             }  
  57.               
  58.         } catch (Exception e) {  
  59.             e.printStackTrace();  
  60.         }  
  61.         return sb.toString();  
  62.     }  
  63. }  

 效果:

Java代码   收藏代码
  1. select * from user where 1=1 and userName='张三' and sex=1  

 

总结

Java注解不复杂,主要也就这么多东西,知道其实现原理,如何自定义注解,就能读懂别人写的注解,自己也能写了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java注解(Annotation)可以看作是对Java程序元素进行标记的一种方式,通过在代码中使用注解,可以为编译器或工具提供额外的信息或指令。可以将Java注解看作是代码中的一段元数据,可提供代码补全、自动检查、文档生成等功能。 在Java中,通过定义注解的方式来使用注解注解可以被定义为类、方法、变量、参数等。每一种注解有着与之对应的元素,程序员可以将注解标记在相应的元素上。 在程序运行时,可以通过反射机制获取注解的信息,并根据注解信息进行相应的处理。可以为注解定义处理器,根据注解信息来执行相应的处理逻辑。 在实例注解时,需要使用注解定义的语法,并通过传递注解参数来构造注解实例注解参数可以是原始类型、String、Class、枚举类型、注解类型以及它们的数组类型。Java在编译时对注解进行检查,如果注解参数类型不合法,则会在编译时抛出异常。 例如,如果要定义一个自定义注解,可以使用如下语法: public @interface MyAnnotation { String value() default ""; int id() default -1; boolean required() default false; } 然后,可以在需要使用注解的地方使用该注解: @MyAnnotation(id = 1, value = "example", required = true) public class MyClass { // class contents } 在这个例子中,我们定义了一个自定义注解MyAnnotation,它有三个参数:value(一个字符串类型的参数,默认为空字符串)、id(一个整数类型的参数,默认为-1)、required(一个布尔类型的参数,默认为false)。然后,我们在MyClass类上使用了该注解,并传递了相应的参数。当程序运行时,我们可以通过反射获取该注解的值,并根据需要进行处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值