[关闭]
@Yano 2016-10-04T03:07:12.000000Z 字数 2000 阅读 1775

Java 注解

Java


注解

最近在研究Java注解,我所理解的Java注解是:注入类的一种标记,向类中方便地配置信息。注解是一个接口,可以由反射自动获取(class.getAnnotation)。

简单实例

接口定义

  1. package com.yano;
  2. import java.lang.annotation.ElementType;
  3. import java.lang.annotation.Retention;
  4. import java.lang.annotation.RetentionPolicy;
  5. import java.lang.annotation.Target;
  6. @Target(ElementType.TYPE)
  7. @Retention(RetentionPolicy.RUNTIME)
  8. public @interface TestAnnotation {
  9. int count() default 1;
  10. String name() default "yano";
  11. }

接口使用

  1. package com.yano;
  2. @TestAnnotation(count = 5, name = "Haha")
  3. public class test {
  4. public static void main(String[] args) {
  5. TestAnnotation annotation = test.class
  6. .getAnnotation(TestAnnotation.class);
  7. System.out.println(annotation.count());
  8. System.out.println(annotation.name());
  9. }
  10. }

运行结果

  1. 5
  2. Haha

分析

使用注解,本质上就是更方便地向类中配置信息。在配置信息时,只需要指定:

  1. @TestAnnotation(count = 5, name = "Haha")

就能够为类配置和加入countname两个变量。注解实际上是一个接口——count和name正是接口所定义的两个变量。在实际使用时,需要通过class方法获取注解:

  1. TestAnnotation annotation = test.class.getAnnotation(TestAnnotation.class);

源码分析

class中获取指定的注解,注解是与类绑定的。

  1. /**
  2. * @throws NullPointerException {@inheritDoc}
  3. * @since 1.5
  4. */
  5. public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
  6. if (annotationClass == null)
  7. throw new NullPointerException();
  8. initAnnotationsIfNecessary();
  9. return (A) annotations.get(annotationClass);
  10. }
  1. // Annotations cache
  2. private transient Map<Class, Annotation> annotations;
  3. private transient Map<Class, Annotation> declaredAnnotations;
  4. private synchronized void initAnnotationsIfNecessary() {
  5. clearCachesOnClassRedefinition();
  6. if (annotations != null)
  7. return;
  8. declaredAnnotations = AnnotationParser.parseAnnotations(
  9. getRawAnnotations(), getConstantPool(), this);
  10. Class<?> superClass = getSuperclass();
  11. if (superClass == null) {
  12. annotations = declaredAnnotations;
  13. } else {
  14. annotations = new HashMap<Class, Annotation>();
  15. superClass.initAnnotationsIfNecessary();
  16. for (Map.Entry<Class, Annotation> e : superClass.annotations.entrySet()) {
  17. Class annotationClass = e.getKey();
  18. if (AnnotationType.getInstance(annotationClass).isInherited())
  19. annotations.put(annotationClass, e.getValue());
  20. }
  21. annotations.putAll(declaredAnnotations);
  22. }
  23. }

思考

一个类是否可以有多个注解?

答:可以。向同一个类中,加入多个数据,为什么不可以呢?只是同一个注解只能使用一次。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注