Java Code Examples for java.lang.annotation.RetentionPolicy

The following are top voted examples for showing how to use java.lang.annotation.RetentionPolicy. 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: GitHub   File: IncludeTypes.java   View source code 6 votes vote down vote up
void use() {
  // this immutable type (package style used)
  ImIncludeTypes.builder().build();
  // included on this type (package style used)
  ImSerializable.builder().build();
  // included on package (package style used)
  ImTicker.builder().read(1).build();

  // included in IncludeNestedTypes
  ImmutableIncludeNestedTypes.Retention retention =
      ImmutableIncludeNestedTypes.Retention.builder()
          .value(RetentionPolicy.CLASS)
          .build();

  // included in IncludeNestedTypes
  ImmutableIncludeNestedTypes.Target target =
      ImmutableIncludeNestedTypes.Target.builder()
          .value(ElementType.CONSTRUCTOR, ElementType.ANNOTATION_TYPE)
          .build();

  // package applied style "copyWith*" test
  // see PackageStyle
  retention.copyWithValue(RetentionPolicy.RUNTIME);
  target.copyWithValue(ElementType.CONSTRUCTOR, ElementType.LOCAL_VARIABLE);
}
 
Example 2
Project: GitHub   File: UseImmutableCollections.java   View source code 6 votes vote down vote up
default void use() {

    ImmutableUseImmutableCollections.builder()
        .addList("a", "b")
        .addSet(1, 2)
        .addEnumSet(RetentionPolicy.CLASS)
        .addSortedSet(RetentionPolicy.RUNTIME)
        .addMultiset("c", "c")
        .putMap("d", 1)
        .putEnumMap(RetentionPolicy.RUNTIME, 2)
        .putSortedMap(RetentionPolicy.SOURCE, 3)
        .putMultimap("e", 2)
        .putSetMultimap("f", 5)
        .putListMultimap("g", 6)
        .build();
  }
 
Example 3
Project: GitHub   File: JdkOnlyTest.java   View source code 6 votes vote down vote up
@Test
public void collections() {
  ImmutableJdkColl coll = ImmutableJdkColl.builder()
      .addInts(1)
      .addInts(2, 3)
      .addAllInts(Arrays.asList(4, 5, 6))
      .addNavs(1, 2, 3)
      .addOrds(4, 6, 5)
      .addAllOrds(Arrays.asList(8, 7, 9))
      .addPols(RetentionPolicy.RUNTIME, RetentionPolicy.RUNTIME)
      .build();

  check(coll.ints()).isOf(1, 2, 3, 4, 5, 6);
  check(coll.navs()).isOf(3, 2, 1);
  check(coll.ords()).isOf(4, 5, 6, 7, 8, 9);
  check(coll.pols()).isOf(RetentionPolicy.RUNTIME);
}
 
Example 4
Project: GitHub   File: FactoryParametersAndSwitcherTest.java   View source code 6 votes vote down vote up
@Test
public void switcher() {

  check(Factory4Builder.newBuilder(4)
      .runtimePolicy()
      .sourcePolicy()
      .classPolicy()
      .build()).is("" + RetentionPolicy.CLASS + 4);

  check(Factory4Builder.newBuilder(42)
      .sourcePolicy()
      .runtimePolicy()
      .build()).is("" + RetentionPolicy.RUNTIME + 42);

  try {
    Factory4Builder.newBuilder(44).build();
    check(false);
  } catch (IllegalStateException ex) {
  }
}
 
Example 5
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 6
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 7
Project: openjdk-jdk10   File: ClassMembersTest.java   View source code 6 votes vote down vote up
@Test(dataProvider = "retentionPolicyTestCase")
public void annotationTest(RetentionPolicy policy) {
    assertEval("import java.lang.annotation.*;");
    String annotationSource =
            "@Retention(RetentionPolicy." + policy.toString() + ")\n" +
            "@interface A {}";
    assertEval(annotationSource);
    String classSource =
            "@A class C {\n" +
            "   @A C() {}\n" +
            "   @A void f() {}\n" +
            "   @A int f;\n" +
            "   @A class Inner {}\n" +
            "}";
    assertEval(classSource);
    String isRuntimeVisible = policy == RetentionPolicy.RUNTIME ? "true" : "false";
    assertEval("C.class.getAnnotationsByType(A.class).length > 0;", isRuntimeVisible);
    assertEval("C.class.getDeclaredConstructor().getAnnotationsByType(A.class).length > 0;", isRuntimeVisible);
    assertEval("C.class.getDeclaredMethod(\"f\").getAnnotationsByType(A.class).length > 0;", isRuntimeVisible);
    assertEval("C.class.getDeclaredField(\"f\").getAnnotationsByType(A.class).length > 0;", isRuntimeVisible);
    assertEval("C.Inner.class.getAnnotationsByType(A.class).length > 0;", isRuntimeVisible);
}
 
Example 8
Project: openjdk-jdk10   File: AnnotationDefaultTest.java   View source code 6 votes vote down vote up
public void test() throws TestFailedException {
    try {
        String template = getSource(getSourceFile(templateFileName));
        for (int i = 0; i < 2; ++i) {
            for (String repeatable : new String[] {"", "@Repeatable(Container.class)"}) {
                for (RetentionPolicy policy : RetentionPolicy.values()) {
                    final int finalI = i;
                    Map<String, String> replacements = new HashMap<String, String>(){{
                        put("%POLICY%", policy.toString());
                        if (finalI != 0) {
                            put("default.*\n", ";\n");
                        }
                        put("%REPEATABLE%", repeatable);
                    }};
                    test(template, replacements, i == 0);
                }
            }
        }
    } catch (Throwable e) {
        addFailure(e);
    } finally {
        checkStatus();
    }
}
 
Example 9
Project: openjdk-jdk10   File: RuntimeAnnotationsTestBase.java   View source code 6 votes vote down vote up
private void testAttributes(
        TestCase.TestMemberInfo member,
        ClassFile classFile,
        Supplier<Attributes> attributes)
        throws ConstantPoolException {
    Map<String, Annotation> actualInvisible = collectAnnotations(
            classFile,
            member,
            attributes.get(),
            Attribute.RuntimeInvisibleAnnotations);
    Map<String, Annotation> actualVisible = collectAnnotations(
            classFile,
            member,
            attributes.get(),
            Attribute.RuntimeVisibleAnnotations);

    checkEquals(actualInvisible.keySet(),
            member.getRuntimeInvisibleAnnotations(), "RuntimeInvisibleAnnotations");
    checkEquals(actualVisible.keySet(),
            member.getRuntimeVisibleAnnotations(), "RuntimeVisibleAnnotations");

    for (TestAnnotationInfo expectedAnnotation : member.annotations.values()) {
        RetentionPolicy policy = getRetentionPolicy(expectedAnnotation.annotationName);
        if (policy == RetentionPolicy.SOURCE) {
            continue;
        }
        printf("Testing: isVisible: %s %s%n", policy.toString(), expectedAnnotation.annotationName);
        Annotation actualAnnotation =
                (policy == RetentionPolicy.RUNTIME ? actualVisible : actualInvisible)
                        .get(expectedAnnotation.annotationName);
        if (checkNotNull(actualAnnotation, "Annotation is found : "
                + expectedAnnotation.annotationName)) {
            expectedAnnotation.testAnnotation(this, classFile, actualAnnotation);
        }
    }
}
 
Example 10
Project: openjdk9   File: ClassMembersTest.java   View source code 6 votes vote down vote up
@Test(enabled = false) // TODO 8080354
public void annotationTest() {
    assertEval("import java.lang.annotation.*;");
    for (RetentionPolicy policy : RetentionPolicy.values()) {
        String annotationSource =
                "@Retention(RetentionPolicy." + policy.toString() + ")\n" +
                "@interface A {}";
        assertEval(annotationSource);
        String classSource =
                "@A class C {\n" +
                "   @A C() {}\n" +
                "   @A void f() {}\n" +
                "   @A int f;\n" +
                "   @A class Inner {}\n" +
                "}";
        assertEval(classSource);
        String isRuntimeVisible = policy == RetentionPolicy.RUNTIME ? "true" : "false";
        assertEval("C.class.getAnnotationsByType(A.class).length > 0;", isRuntimeVisible);
        assertEval("C.class.getDeclaredConstructor().getAnnotationsByType(A.class).length > 0;", isRuntimeVisible);
        assertEval("C.class.getDeclaredMethod(\"f\").getAnnotationsByType(A.class).length > 0;", isRuntimeVisible);
        assertEval("C.class.getDeclaredField(\"f\").getAnnotationsByType(A.class).length > 0;", isRuntimeVisible);
        assertEval("C.Inner.class.getAnnotationsByType(A.class).length > 0;", isRuntimeVisible);
    }
}
 
Example 11
Project: openjdk9   File: AnnotationDefaultTest.java   View source code 6 votes vote down vote up
public void test() throws TestFailedException {
    try {
        String template = getSource(getSourceFile(templateFileName));
        for (int i = 0; i < 2; ++i) {
            for (String repeatable : new String[] {"", "@Repeatable(Container.class)"}) {
                for (RetentionPolicy policy : RetentionPolicy.values()) {
                    final int finalI = i;
                    Map<String, String> replacements = new HashMap<String, String>(){{
                        put("%POLICY%", policy.toString());
                        if (finalI != 0) {
                            put("default.*\n", ";\n");
                        }
                        put("%REPEATABLE%", repeatable);
                    }};
                    test(template, replacements, i == 0);
                }
            }
        }
    } catch (Throwable e) {
        addFailure(e);
    } finally {
        checkStatus();
    }
}
 
Example 12
Project: huntbugs   File: NoRuntimeRetention.java   View source code 6 votes vote down vote up
@AstVisitor(nodes = AstNodes.EXPRESSIONS)
public void visit(Expression expr, MethodContext mc, DeclaredAnnotations da) {
    if (expr.getCode() == AstCode.InvokeVirtual && expr.getArguments().size() == 2) {
        MethodReference mr = (MethodReference) expr.getOperand();
        if ((mr.getDeclaringType().getInternalName().startsWith("java/lang/reflect/") || mr.getDeclaringType()
                .getInternalName().equals("java/lang/Class")) && mr.getName().contains("Annotation")) {
            Object constant = Nodes.getConstant(expr.getArguments().get(1));
            if (constant instanceof TypeReference) {
                TypeReference tr = (TypeReference) constant;
                DeclaredAnnotation annot = da.get(tr);
                if (annot != null && annot.getPolicy() != RetentionPolicy.RUNTIME) {
                    mc.report("AnnotationNoRuntimeRetention", 0, expr, ANNOTATION.create(tr));
                }
            }
        }
    }
}
 
Example 13
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 14
Project: turbine   File: ConstBinder.java   View source code 6 votes vote down vote up
static AnnotationMetadata bindAnnotationMetadata(
    TurbineTyKind kind, Iterable<AnnoInfo> annotations) {
  if (kind != TurbineTyKind.ANNOTATION) {
    return null;
  }
  RetentionPolicy retention = null;
  ImmutableSet<ElementType> target = null;
  ClassSymbol repeatable = null;
  for (AnnoInfo annotation : annotations) {
    switch (annotation.sym().binaryName()) {
      case "java/lang/annotation/Retention":
        retention = bindRetention(annotation);
        break;
      case "java/lang/annotation/Target":
        target = bindTarget(annotation);
        break;
      case "java/lang/annotation/Repeatable":
        repeatable = bindRepeatable(annotation);
        break;
      default:
        break;
    }
  }
  return new AnnotationMetadata(retention, target, repeatable);
}
 
Example 15
Project: turbine   File: BytecodeBoundClass.java   View source code 6 votes vote down vote up
@Override
public AnnotationMetadata get() {
  if ((access() & TurbineFlag.ACC_ANNOTATION) != TurbineFlag.ACC_ANNOTATION) {
    return null;
  }
  RetentionPolicy retention = null;
  ImmutableSet<ElementType> target = null;
  ClassSymbol repeatable = null;
  for (ClassFile.AnnotationInfo annotation : classFile.get().annotations()) {
    switch (annotation.typeName()) {
      case "Ljava/lang/annotation/Retention;":
        retention = bindRetention(annotation);
        break;
      case "Ljava/lang/annotation/Target;":
        target = bindTarget(annotation);
        break;
      case "Ljava/lang/annotation/Repeatable;":
        repeatable = bindRepeatable(annotation);
        break;
      default:
        break;
    }
  }
  return new AnnotationMetadata(retention, target, repeatable);
}
 
Example 16
Project: Lyrics   File: TypeModel.java   View source code 6 votes vote down vote up
public TypeModel(Type type, Modifier[] modifiers, VariableModel extendsType, Set<VariableModel> interfaces, List<GenericVariableModel> genericVariables, List<AnnotationModel> annotations, Map<String, FieldModel> fields, Map<String, MethodModel> methods, InclusionType inclusion, List<String> values, Map<String, Object[]> valuesWithFields, List<String> fieldOrder, SubTypeModel subTypes, RetentionPolicy retention, ElementType[] elementTypes, List<String> customConstructorFields) {
    this.type = type;
    this.modifiers = modifiers;
    this.extendsType = extendsType;
    this.interfaces = interfaces;
    this.genericVariables = genericVariables;
    this.annotations = annotations;
    this.fields = fields;
    this.methods = methods;
    this.inclusion = inclusion;
    this.values = values;
    this.valuesWithFields = valuesWithFields;
    this.fieldOrder = fieldOrder;
    this.subTypes = subTypes;
    this.retention = retention;
    this.elementTypes = elementTypes;
    this.customConstructorFields = customConstructorFields;
}
 
Example 17
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 18
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 19
Project: intellij-ce-playground   File: ClassRepr.java   View source code 6 votes vote down vote up
public ClassRepr(final DependencyContext context, final int a, final int fn, final int n, final int sig,
                 final int sup,
                 final String[] i,
                 final Set<FieldRepr> f,
                 final Set<MethodRepr> m,
                 final Set<ElemType> targets,
                 final RetentionPolicy policy,
                 final int outerClassName,
                 final boolean localClassFlag,
                 final boolean anonymousClassFlag,
                 final Set<UsageRepr.Usage> usages) {
  super(a, sig, n);
  this.myContext = context;
  myFileName = fn;
  mySuperClass = TypeRepr.createClassType(context, sup);
  myInterfaces = (Set<TypeRepr.AbstractType>)TypeRepr.createClassType(context, i, new THashSet<TypeRepr.AbstractType>(1));
  myFields = f;
  myMethods = m;
  this.myAnnotationTargets = targets;
  this.myRetentionPolicy = policy;
  this.myOuterClassName = outerClassName;
  this.myIsLocal = localClassFlag;
  this.myIsAnonymous = anonymousClassFlag;
  this.myUsages = usages;
}
 
Example 20
Project: intellij-ce-playground   File: ClassRepr.java   View source code 6 votes vote down vote up
public ClassRepr(final DependencyContext context, final DataInput in) {
  super(in);
  try {
    this.myContext = context;
    myFileName = DataInputOutputUtil.readINT(in);
    mySuperClass = (TypeRepr.ClassType)TypeRepr.externalizer(context).read(in);
    myInterfaces = (Set<TypeRepr.AbstractType>)RW.read(TypeRepr.externalizer(context), new THashSet<TypeRepr.AbstractType>(1), in);
    myFields = (Set<FieldRepr>)RW.read(FieldRepr.externalizer(context), new THashSet<FieldRepr>(), in);
    myMethods = (Set<MethodRepr>)RW.read(MethodRepr.externalizer(context), new THashSet<MethodRepr>(), in);
    myAnnotationTargets = (Set<ElemType>)RW.read(UsageRepr.AnnotationUsage.elementTypeExternalizer, EnumSet.noneOf(ElemType.class), in);

    final String s = RW.readUTF(in);

    myRetentionPolicy = s.length() == 0 ? null : RetentionPolicy.valueOf(s);

    myOuterClassName = DataInputOutputUtil.readINT(in);
    int flags = DataInputOutputUtil.readINT(in);
    myIsLocal = (flags & LOCAL_MASK) != 0;
    myIsAnonymous = (flags & ANONYMOUS_MASK) != 0;
    myUsages =(Set<UsageRepr.Usage>)RW.read(UsageRepr.externalizer(context), new THashSet<UsageRepr.Usage>(), in);
  }
  catch (IOException e) {
    throw new BuildDataCorruptedException(e);
  }
}
 
Example 21
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 22
Project: intellij-ce-playground   File: AnnotationsHighlightUtil.java   View source code 6 votes vote down vote up
@Nullable
public static RetentionPolicy getRetentionPolicy(@NotNull PsiClass annotation) {
  PsiModifierList modifierList = annotation.getModifierList();
  if (modifierList != null) {
    PsiAnnotation retentionAnno = modifierList.findAnnotation(CommonClassNames.JAVA_LANG_ANNOTATION_RETENTION);
    if (retentionAnno == null) return RetentionPolicy.CLASS;

    PsiAnnotationMemberValue policyRef = PsiImplUtil.findAttributeValue(retentionAnno, null);
    if (policyRef instanceof PsiReference) {
      PsiElement field = ((PsiReference)policyRef).resolve();
      if (field instanceof PsiEnumConstant) {
        String name = ((PsiEnumConstant)field).getName();
        try {
          return Enum.valueOf(RetentionPolicy.class, name);
        }
        catch (Exception e) {
          LOG.warn("Unknown policy: " + name);
        }
      }
    }
  }

  return null;
}
 
Example 23
Project: Diorite   File: Controller.java   View source code 6 votes vote down vote up
@Override
protected Map<Class<? extends Annotation>, ? extends Annotation> extractRawScopeAnnotations(AnnotatedCodeElement element)
{
    Annotation[] annotations = AsmUtils.getAnnotations(element, RetentionPolicy.RUNTIME);
    Map<Class<? extends Annotation>, Annotation> resultMap = new HashMap<>(annotations.length + 1);
    for (Annotation annotation : annotations)
    {
        Class<? extends Annotation> annotationType = annotation.annotationType();
        if (annotationType.isAnnotationPresent(Scope.class))
        {
            if (resultMap.containsKey(annotationType))
            {
                throw new IllegalStateException("Duplicated scope! Found: " + annotation + ", others: " + resultMap);
            }
            resultMap.put(annotationType, annotation);
        }
    }
    return resultMap;
}
 
Example 24
Project: j2objc   File: BindingUtil.java   View source code 6 votes vote down vote up
/**
 * Returns true if the specified binding is of an annotation that has
 * a runtime retention policy.
 */
public static boolean isRuntimeAnnotation(ITypeBinding binding) {
  if (binding != null && binding.isAnnotation()) {
    for (IAnnotationBinding ann : binding.getAnnotations()) {
      if (ann.getName().equals("Retention")) {
        IVariableBinding retentionBinding =
            (IVariableBinding) ann.getDeclaredMemberValuePairs()[0].getValue();
        return retentionBinding.getName().equals(RetentionPolicy.RUNTIME.name());
      }
    }
    if (binding.isNested()) {
      return BindingUtil.isRuntimeAnnotation(binding.getDeclaringClass());
    }
  }
  return false;
}
 
Example 25
Project: annotation-tools   File: JavapParser.java   View source code 6 votes vote down vote up
private void parseAnnotationSection(AElement member, AnnotationSection sec) throws IOException, ParseException {
    // FILL
    while (inData()) {
        String annoTypeName = parseAnnotationHead();
        RetentionPolicy retention = sec.retention;
        AnnotationBuilder ab = AnnotationFactory.saf.beginAnnotation(annoTypeName, Annotations.getRetentionPolicyMetaAnnotationSet(retention));
        if (ab == null) {
            // don't care about the result
            // but need to skip over it anyway
            parseAnnotationBody(
                    AnnotationFactory.saf.beginAnnotation(annoTypeName, Annotations.noAnnotations),
                    SECTION_DATA_PREFIX);
        } else {
            // Wrap it in a TLA with the appropriate retention policy
            Annotation a = parseAnnotationBody(ab, SECTION_DATA_PREFIX);
            // Now we need to parse the location information to determine
            // which element gets the annotation.
            AElement annoMember = chooseSubElement(member, sec);
            annoMember.tlAnnotationsHere.add(a);
        }
    }
}
 
Example 26
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 27
Project: In-the-Box-Fork   File: RetentionPolicyTest.java   View source code 6 votes vote down vote up
/**
 * @throws Exception
 * @tests java.lang.annotation.RetentionPolicy#valueOf(String)
 */
@SuppressWarnings("nls")
public void test_valueOfLjava_lang_String() throws Exception {
    assertSame(RetentionPolicy.CLASS, RetentionPolicy
            .valueOf("CLASS"));
    assertSame(RetentionPolicy.RUNTIME, RetentionPolicy
            .valueOf("RUNTIME"));
    assertSame(RetentionPolicy.SOURCE, RetentionPolicy
            .valueOf("SOURCE"));
    try {
        RetentionPolicy.valueOf("OTHER");
        fail("Should throw an IllegalArgumentException");
    } catch (IllegalArgumentException e) {
        // expected
    }
}
 
Example 28
Project: cn1   File: RetentionPolicyTest.java   View source code 6 votes vote down vote up
/**
 * @throws Exception
 * @tests java.lang.annotation.RetentionPolicy#valueOf(String)
 */
@SuppressWarnings("nls")
public void test_valueOfLjava_lang_String() throws Exception {
    assertSame(RetentionPolicy.CLASS, RetentionPolicy
            .valueOf("CLASS"));
    assertSame(RetentionPolicy.RUNTIME, RetentionPolicy
            .valueOf("RUNTIME"));
    assertSame(RetentionPolicy.SOURCE, RetentionPolicy
            .valueOf("SOURCE"));
    try {
        RetentionPolicy.valueOf("OTHER");
        fail("Should throw an IllegalArgumentException");
    } catch (IllegalArgumentException e) {
        // expected
    }
}
 
Example 29
Project: JSONschema4-mapper   File: CustomReferenceNameProviderTest.java   View source code 6 votes vote down vote up
@Test
public void enumReferenceTest() throws Exception {
    //given
    final String prefix = "c>";
    mapper.setReferenceNameProvider(new DefaultReferenceNameProvider() {
        @Override
        protected String getPrefix() {
            return prefix;
        }
    });

    //when
    final JSONObject schema = mapper.toJsonSchema4(Empty.class);

    //then
    final String enumRef = schema.getJSONObject("properties").getJSONObject("policy").getString("$ref");
    assertThat(enumRef, equalTo(prefix + RetentionPolicy.class.getSimpleName()));
}
 
Example 30
Project: tools-idea   File: ClassRepr.java   View source code 6 votes vote down vote up
public ClassRepr(final DependencyContext context, final int a, final int fn, final int n, final int sig,
                 final int sup,
                 final String[] i,
                 final Set<FieldRepr> f,
                 final Set<MethodRepr> m,
                 final Set<ElemType> targets,
                 final RetentionPolicy policy,
                 final int outerClassName,
                 final boolean localClassFlag,
                 final boolean anonymousClassFlag,
                 final Set<UsageRepr.Usage> usages) {
  super(a, sig, n);
  this.myContext = context;
  myFileName = fn;
  mySuperClass = TypeRepr.createClassType(context, sup);
  myInterfaces = (Set<TypeRepr.AbstractType>)TypeRepr.createClassType(context, i, new HashSet<TypeRepr.AbstractType>());
  myFields = f;
  myMethods = m;
  this.myAnnotationTargets = targets;
  this.myRetentionPolicy = policy;
  this.myOuterClassName = outerClassName;
  this.myIsLocal = localClassFlag;
  this.myIsAnonymous = anonymousClassFlag;
  this.myUsages = usages;
}
 
Example 31
Project: tools-idea   File: ClassRepr.java   View source code 6 votes vote down vote up
public ClassRepr(final DependencyContext context, final DataInput in) {
  super(in);
  try {
    this.myContext = context;
    myFileName = in.readInt();
    mySuperClass = (TypeRepr.ClassType)TypeRepr.externalizer(context).read(in);
    myInterfaces = (Set<TypeRepr.AbstractType>)RW.read(TypeRepr.externalizer(context), new HashSet<TypeRepr.AbstractType>(), in);
    myFields = (Set<FieldRepr>)RW.read(FieldRepr.externalizer(context), new HashSet<FieldRepr>(), in);
    myMethods = (Set<MethodRepr>)RW.read(MethodRepr.externalizer(context), new HashSet<MethodRepr>(), in);
    myAnnotationTargets = (Set<ElemType>)RW.read(UsageRepr.AnnotationUsage.elementTypeExternalizer, EnumSet.noneOf(ElemType.class), in);

    final String s = in.readUTF();

    myRetentionPolicy = s.length() == 0 ? null : RetentionPolicy.valueOf(s);

    myOuterClassName = in.readInt();
    myIsLocal = in.readBoolean();
    myIsAnonymous = in.readBoolean();
    myUsages =(Set<UsageRepr.Usage>)RW.read(UsageRepr.externalizer(context), new HashSet<UsageRepr.Usage>(), in);
  }
  catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 32
Project: tools-idea   File: AnnotationsHighlightUtil.java   View source code 6 votes vote down vote up
@Nullable
private static RetentionPolicy getRetentionPolicy(PsiClass annotation) {
  PsiModifierList modifierList = annotation.getModifierList();
  if (modifierList != null) {
    PsiAnnotation retentionAnno = modifierList.findAnnotation(CommonClassNames.JAVA_LANG_ANNOTATION_RETENTION);
    if (retentionAnno == null) return RetentionPolicy.CLASS;

    PsiAnnotationMemberValue policyRef = PsiImplUtil.findAttributeValue(retentionAnno, null);
    if (policyRef instanceof PsiReference) {
      PsiElement field = ((PsiReference)policyRef).resolve();
      if (field instanceof PsiEnumConstant) {
        String name = ((PsiEnumConstant)field).getName();
        try {
          return RetentionPolicy.valueOf(name);
        }
        catch (Exception e) {
          LOG.warn("Unknown policy: " + name);
        }
      }
    }
  }

  return null;
}
 
Example 33
Project: Dyvil   File: AnnotationMetadata.java   View source code 6 votes vote down vote up
private void readRetention()
{
	final Annotation retention = this.theClass.getAnnotation(Annotation.LazyFields.RETENTION_CLASS);
	if (retention == null)
	{
		return;
	}

	final IValue value = retention.getArguments().get(0, Names.value);
	if (!(value instanceof EnumValue))
	{
		return;
	}

	try
	{
		final String name = ((EnumValue) value).getName().qualified;
		this.retention = RetentionPolicy.valueOf(name);
	}
	catch (IllegalArgumentException ignored)
	{
		// Problematic RetentionPolicy annotation - do not handle this
	}
}
 
Example 34
Project: freeVM   File: RetentionPolicyTest.java   View source code 6 votes vote down vote up
/**
 * @throws Exception
 * @tests java.lang.annotation.RetentionPolicy#valueOf(String)
 */
@SuppressWarnings("nls")
public void test_valueOfLjava_lang_String() throws Exception {
    assertSame(RetentionPolicy.CLASS, RetentionPolicy
            .valueOf("CLASS"));
    assertSame(RetentionPolicy.RUNTIME, RetentionPolicy
            .valueOf("RUNTIME"));
    assertSame(RetentionPolicy.SOURCE, RetentionPolicy
            .valueOf("SOURCE"));
    try {
        RetentionPolicy.valueOf("OTHER");
        fail("Should throw an IllegalArgumentException");
    } catch (IllegalArgumentException e) {
        // expected
    }
}
 
Example 35
Project: freeVM   File: RetentionPolicyTest.java   View source code 6 votes vote down vote up
/**
 * @throws Exception
 * @tests java.lang.annotation.RetentionPolicy#valueOf(String)
 */
@SuppressWarnings("nls")
public void test_valueOfLjava_lang_String() throws Exception {
    assertSame(RetentionPolicy.CLASS, RetentionPolicy
            .valueOf("CLASS"));
    assertSame(RetentionPolicy.RUNTIME, RetentionPolicy
            .valueOf("RUNTIME"));
    assertSame(RetentionPolicy.SOURCE, RetentionPolicy
            .valueOf("SOURCE"));
    try {
        RetentionPolicy.valueOf("OTHER");
        fail("Should throw an IllegalArgumentException");
    } catch (IllegalArgumentException e) {
        // expected
    }
}
 
Example 36
Project: byte-buddy   File: MethodAttributeAppenderForInstrumentedMethodTest.java   View source code 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testJdkTypeIsFiltered() throws Exception {
    when(annotationValueFilter.isRelevant(any(AnnotationDescription.class), any(MethodDescription.InDefinedShape.class))).thenReturn(true);
    AnnotationDescription annotationDescription = mock(AnnotationDescription.class);
    TypeDescription annotationType = mock(TypeDescription.class);
    when(annotationType.getDeclaredMethods()).thenReturn(new MethodList.Empty<MethodDescription.InDefinedShape>());
    when(annotationDescription.getRetention()).thenReturn(RetentionPolicy.RUNTIME);
    when(annotationDescription.getAnnotationType()).thenReturn(annotationType);
    when(annotationType.getActualName()).thenReturn("jdk.internal.Sample");
    when(methodDescription.getDeclaredAnnotations()).thenReturn(new AnnotationList.Explicit(annotationDescription));
    when(methodDescription.getParameters()).thenReturn((ParameterList) new ParameterList.Empty<ParameterDescription>());
    when(methodDescription.getReturnType()).thenReturn(TypeDescription.Generic.VOID);
    when(methodDescription.getTypeVariables()).thenReturn(new TypeList.Generic.Empty());
    when(methodDescription.getExceptionTypes()).thenReturn(new TypeList.Generic.Empty());
    methodAttributeAppender.apply(methodVisitor, methodDescription, annotationValueFilter);
    verifyZeroInteractions(methodVisitor);
}
 
Example 37
Project: byte-buddy   File: TypeWriterFieldPoolRecordTest.java   View source code 6 votes vote down vote up
@Before
@SuppressWarnings("unchecked")
public void setUp() throws Exception {
    when(fieldDescription.getActualModifiers()).thenReturn(MODIFIER);
    when(fieldDescription.getInternalName()).thenReturn(FOO);
    when(fieldDescription.getDescriptor()).thenReturn(BAR);
    when(fieldDescription.getGenericSignature()).thenReturn(QUX);
    when(fieldDescription.getDeclaredAnnotations()).thenReturn(new AnnotationList.Explicit(annotationDescription));
    when(fieldDescription.getType()).thenReturn(TypeDescription.Generic.OBJECT);
    when(classVisitor.visitField(MODIFIER, FOO, BAR, QUX, defaultValue)).thenReturn(fieldVisitor);
    when(classVisitor.visitField(MODIFIER, FOO, BAR, QUX, FieldDescription.NO_DEFAULT_VALUE)).thenReturn(fieldVisitor);
    when(annotationValueFilterFactory.on(fieldDescription)).thenReturn(valueFilter);
    when(fieldVisitor.visitAnnotation(any(String.class), anyBoolean())).thenReturn(annotationVisitor);
    when(annotationDescription.getAnnotationType()).thenReturn(annotationType);
    when(annotationType.getDescriptor()).thenReturn(BAZ);
    when(annotationType.getDeclaredMethods()).thenReturn(new MethodList.Empty<MethodDescription.InDefinedShape>());
    when(annotationDescription.getRetention()).thenReturn(RetentionPolicy.RUNTIME);
}
 
Example 38
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 39
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 40
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());
}