java注解

来源:互联网 发布:js对象转换成json 编辑:程序博客网 时间:2024/05/29 07:03

1. JDK自带注解

@Override 

@Deprecated

@Suppvisewarnings


2.  其他注解-Spring常见注解

@Autowired

@Service

@Repository


3.   其他注解-Mybatis常见注解

@InsertProvider

@UpdateProvider

@Options


4. 注解的分类

源码注解:注解只在源码中存在,编译成.class文件就不存在了

编译时注解:注解在源码和.class文件中都存在(例:JDK自带注解@Override)

运行时注解:在运行阶段还起作用,甚至会影响运行逻辑的注解(例:spring的 @Autowired)


5.自定义注解的语法要求

(1)使用@interface关键字自定义注解

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

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

(4)成员类型是受限制的,合法的类型包括原始类型及String , Class , Annotation, Enumeration

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

(6)注解类可以没有成员,没有成员的注解称为标识注解


6. 元注解

(1)@Target({})   注解的作用域

(2)@Retention  注解的声明周期

(3)@Inherited    允许子注解继承 

(4)@Documented 生成javadoc时包含注解信息


7. 使用注解的语法:

@<注解名>(<成员名1>=<成员值1> , <成员名1>=<成员值1>,….)


8.解析注解

通过反射获取类、函数或成员上的运行时注解信息,从而实现动态控制程序运行的逻辑


下面通过两个例子讲解如何使用以及定义注解

Person接口

public interface Person {public String name();}

Child类实现了Persos接口,并且使用了注解

@Description(author = "chenhong", desc = "an annotataion in class")public class Child implements Person {@Override@Description(author = "chenhong", desc = "an annotation in method")public String name() {// TODO Auto-generated method stubreturn null;}}

自定义Description注解

@Target({ ElementType.METHOD, ElementType.TYPE })@Retention(RetentionPolicy.RUNTIME)@Inherited@Documentedpublic @interface Description {String desc();String author();int age() default 18;}

测试

import java.lang.annotation.Annotation;import java.lang.reflect.Method;public class ParseAnnnotation {public static void main(String[] args) {// 使用类加载器加载类try {Class child = Class.forName("Child");// 找到类上面的注解boolean isExist = child.isAnnotationPresent(Description.class);if (isExist) {// 拿到注解实例Description d = (Description) child.getAnnotation(Description.class);System.out.println("author:" + d.author() + " desc:" + d.desc());}// 找到方法上的注解Method[] methods = child.getMethods();for (Method m : methods) {boolean isMExist = m.isAnnotationPresent(Description.class);if (isMExist) {Description d = (Description) m.getAnnotation(Description.class);System.out.println("author:" + d.author() + " desc:"+ d.desc());}}// 另外一种解析方法for (Method m : methods) {Annotation[] as = m.getAnnotations();for (Annotation a : as) {if (a instanceof Description) {Description d = (Description) a;System.out.println("author:" + d.author() + " desc:"+ d.desc());}}}} catch (ClassNotFoundException e) {e.printStackTrace();}}}


源代码:  http://download.csdn.net/detail/ch717828/8959057



0 0