微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java.lang.annotation.RetentionPolicy的实例源码

项目:GitHub    文件IncludeTypes.java   
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);
}
项目:GitHub    文件UseImmutableCollections.java   
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();
  }
项目:GitHub    文件JdkOnlyTest.java   
@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,3,4,6);
  check(coll.navs()).isOf(3,1);
  check(coll.ords()).isOf(4,8,9);
  check(coll.pols()).isOf(RetentionPolicy.RUNTIME);
}
项目:GitHub    文件FactoryParametersAndSwitcherTest.java   
@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) {
  }
}
项目: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));
            }
        }
    };
}
项目:openjdk-jdk10    文件ClassMembersTest.java   
@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);
}
项目:openjdk-jdk10    文件AnnotationDefaultTest.java   
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();
    }
}
项目:openjdk9    文件ClassMembersTest.java   
@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);
    }
}
项目:openjdk9    文件AnnotationDefaultTest.java   
public void test() throws TestFailedException {
    try {
        String template = getSource(getSourceFile(templateFileName));
        for (int i = 0; i < 2; ++i) {
            for (String repeatable : new String[] {"",i == 0);
                }
            }
        }
    } catch (Throwable e) {
        addFailure(e);
    } finally {
        checkStatus();
    }
}
项目:huntbugs    文件noruntimeRetention.java   
@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",expr,ANNOTATION.create(tr));
                }
            }
        }
    }
}
项目: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());
                        }
                    }
                }
            }
        }
    }
}
项目:turbine    文件ConstBinder.java   
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);
}
项目:turbine    文件BytecodeBoundClass.java   
@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,repeatable);
}
项目:Lyrics    文件TypeModel.java   
public TypeModel(Type type,Modifier[] modifiers,VariableModel extendsType,Set<VariableModel> interfaces,List<GenericVariableModel> genericVariables,List<AnnotationModel> annotations,Map<String,FieldModel> fields,MethodModel> methods,InclusionType inclusion,List<String> values,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;
}
项目: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    文件ClassRepr.java   
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;
}
项目:intellij-ce-playground    文件ClassRepr.java   
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);
  }
}
项目: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;
}
项目:intellij-ce-playground    文件AnnotationsHighlightUtil.java   
@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;
}
项目:diorite    文件Controller.java   
@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;
}
项目:j2objc    文件BindingUtil.java   
/**
 * 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;
}
项目:annotation-tools    文件JavapParser.java   
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 @R_998_4045@ion to determine
            // which element gets the annotation.
            AElement annoMember = chooseSubElement(member,sec);
            annoMember.tlAnnotationsHere.add(a);
        }
    }
}
项目: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());
}
项目:In-the-Box-Fork    文件RetentionPolicyTest.java   
/**
 * @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
    }
}
项目:cn1    文件RetentionPolicyTest.java   
/**
 * @throws Exception
 * @tests java.lang.annotation.RetentionPolicy#valueOf(String)
 */
@SuppressWarnings("nls")
public void test_valueOfLjava_lang_String() throws Exception {
    assertSame(RetentionPolicy.CLASS,RetentionPolicy
            .valueOf("SOURCE"));
    try {
        RetentionPolicy.valueOf("OTHER");
        fail("Should throw an IllegalArgumentException");
    } catch (IllegalArgumentException e) {
        // expected
    }
}
项目:JSONschema4-mapper    文件CustomreferenceNameProviderTest.java   
@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()));
}
项目:tools-idea    文件ClassRepr.java   
public ClassRepr(final DependencyContext context,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;
}
项目:tools-idea    文件ClassRepr.java   
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>(),new HashSet<FieldRepr>(),new HashSet<MethodRepr>(),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);
  }
}
项目:tools-idea    文件AnnotationsHighlightUtil.java   
@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;
}
项目:Dyvil    文件AnnotationMetadata.java   
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
    }
}
项目:freeVM    文件RetentionPolicyTest.java   
/**
 * @throws Exception
 * @tests java.lang.annotation.RetentionPolicy#valueOf(String)
 */
@SuppressWarnings("nls")
public void test_valueOfLjava_lang_String() throws Exception {
    assertSame(RetentionPolicy.CLASS,RetentionPolicy
            .valueOf("SOURCE"));
    try {
        RetentionPolicy.valueOf("OTHER");
        fail("Should throw an IllegalArgumentException");
    } catch (IllegalArgumentException e) {
        // expected
    }
}
项目:byte-buddy    文件MethodAttributeAppenderForInstrumentedMethodTest.java   
@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);
}
项目:byte-buddy    文件TypeWriterFieldPoolRecordTest.java   
@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,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);
}
项目: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,int[].class,Object.class,Serializable.class,RetentionPolicy.class,Retention.class,AnyInterface.class,true);
    assertClasstype(predicate,AnyBaseClass.class,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,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());
}
项目:immutables    文件IncludeTypes.java   
@SuppressWarnings("CheckReturnValue")
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.LOCAL_VARIABLE);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。