@Yano
2016-10-04T03:07:12.000000Z
字数 2000
阅读 2322
Java
最近在研究Java注解,我所理解的Java注解是:注入类的一种标记,向类中方便地配置信息。注解是一个接口,可以由反射自动获取(class.getAnnotation)。
package com.yano;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 TestAnnotation {int count() default 1;String name() default "yano";}
package com.yano;@TestAnnotation(count = 5, name = "Haha")public class test {public static void main(String[] args) {TestAnnotation annotation = test.class.getAnnotation(TestAnnotation.class);System.out.println(annotation.count());System.out.println(annotation.name());}}
5Haha
使用注解,本质上就是更方便地向类中配置信息。在配置信息时,只需要指定:
@TestAnnotation(count = 5, name = "Haha")
就能够为类配置和加入count和name两个变量。注解实际上是一个接口——count和name正是接口所定义的两个变量。在实际使用时,需要通过class方法获取注解:
TestAnnotation annotation = test.class.getAnnotation(TestAnnotation.class);
class中获取指定的注解,注解是与类绑定的。
/*** @throws NullPointerException {@inheritDoc}* @since 1.5*/public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {if (annotationClass == null)throw new NullPointerException();initAnnotationsIfNecessary();return (A) annotations.get(annotationClass);}
// Annotations cacheprivate transient Map<Class, Annotation> annotations;private transient Map<Class, Annotation> declaredAnnotations;private synchronized void initAnnotationsIfNecessary() {clearCachesOnClassRedefinition();if (annotations != null)return;declaredAnnotations = AnnotationParser.parseAnnotations(getRawAnnotations(), getConstantPool(), this);Class<?> superClass = getSuperclass();if (superClass == null) {annotations = declaredAnnotations;} else {annotations = new HashMap<Class, Annotation>();superClass.initAnnotationsIfNecessary();for (Map.Entry<Class, Annotation> e : superClass.annotations.entrySet()) {Class annotationClass = e.getKey();if (AnnotationType.getInstance(annotationClass).isInherited())annotations.put(annotationClass, e.getValue());}annotations.putAll(declaredAnnotations);}}
答:可以。向同一个类中,加入多个数据,为什么不可以呢?只是同一个注解只能使用一次。
