java 注解
2017-03-16 00:00
267 查看
java 1.5开始有了注解,本质上就是一个标示,用于代码间解耦合
jdk中原生(java原生注解)注解
@Overrride(重写父类中的方法)
@SuppressWarnings(消除警告)
@Deprecate(声明方法已经过时)
元注解,用来修饰描述其他注解(注解的注解)
元注解有4个
@Target //标示注解的作用域(type(类),filed(字段),method(方法)....)
@Retention //标示注解的生命周期 (source(存在于java文件),class(存在于java文件和class文件),runtime(代码运行时也存在,可以影响代码逻辑))
@Documented //标示注解是否可以生成java文档
@Inherited //标示注解是否可以被子类继承
自定义注解
所有的注解都会默认是 public interface Annotation 接口的子类,就想所有java类都会是Object的子类一样
jdk中原生(java原生注解)注解
@Overrride(重写父类中的方法)
@SuppressWarnings(消除警告)
@Deprecate(声明方法已经过时)
元注解,用来修饰描述其他注解(注解的注解)
元注解有4个
@Target //标示注解的作用域(type(类),filed(字段),method(方法)....)
@Retention //标示注解的生命周期 (source(存在于java文件),class(存在于java文件和class文件),runtime(代码运行时也存在,可以影响代码逻辑))
@Documented //标示注解是否可以生成java文档
@Inherited //标示注解是否可以被子类继承
自定义注解
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Msg { String default_str = "mgs"; String msg() default default_str; } @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @interface TableFiled { String tablefiled ="這個是表裡面沒有的字段"; String getTbaleFiled() default tablefiled; } @Msg(msg="this is test") public class AnnotationTest { @TableFiled(getTbaleFiled="ceshi---name") private String name; @TableFiled(getTbaleFiled="ceshi---age") private String age; private String address; public String getName() { return name; } public String getAge() { return age; } public String getAddress() { return address; } public void setName(String name) { this.name = name; } public void setAge(String age) { this.age = age; } public void setAddress(String address) { this.address = address; } //mian方法简单的解析,真实项目中,会有与注解对应的注解解析器 public static void main(String[] mgs){ AnnotationTest test = new AnnotationTest(); Msg msgs = (Msg)test.getClass().getAnnotation(Msg.class); System.out.println(msgs.msg()); Field[] fields =test.getClass().getDeclaredFields(); Arrays.asList(fields).forEach( f ->{ TableFiled tableFiled = f.getAnnotation(TableFiled.class); if(!StringUtils.isEmpty(tableFiled)){ System.out.println(tableFiled.getTbaleFiled()); } }); } } 控制台输出 this is test ceshi---name ceshi---age
所有的注解都会默认是 public interface Annotation 接口的子类,就想所有java类都会是Object的子类一样
相关文章推荐
- SCA的java注解和API规范v100
- 在EasyDBO中使用Java注解配置映射的原理及使用
- Java的String经典笔试题付注解
- java之注解(一)
- The Java EE 5Tutorial-Preface(注解)
- java的注解
- 在EasyDBO中使用Java注解配置映射的原理及使用
- java5.0使用annotion注解
- Java注解(Tiger)
- EasyDBO中Java注解配置映射的原理及使用
- 在EasyDBO中使用Java注解配置映射的原理及使用
- 在EasyDBO中使用Java注解配置映射的原理及使用
- Java的String经典笔试题付注解
- 在EasyDBO中使用Java注解配置映射的原理及使用
- EasyDBO中Java注解配置映射的原理及使用
- java annocation(注解)
- 在EasyDBO中使用Java注解配置映射的原理及使用
- 管中窥豹Java5的新特性-注解(@Override)_Thinking in Java(4)_读书笔记(3)
- JAVA Annotation 注解
- java注解