private static <A extends Annotation> A getAnnotation(Class<?> type, Class<A> annotationType, boolean checkType) { A annotation; if (checkType) { annotation = type.getAnnotation(annotationType); if (annotation != null) { return annotation; } } if (annotationType.getAnnotation(Inherited.class) != null) { for (Class<?> anInterface : type.getInterfaces()) { annotation = getAnnotation(anInterface, annotationType, true); if (annotation != null) { return annotation; } } } if (type.isInterface() || type.equals(Object.class)) { return null; } else { return getAnnotation(type.getSuperclass(), annotationType, false); } }
public static Predicate<Class<?>> predicateClassAnnotatedWith( final Class<? extends Annotation> annotation) { if (!annotation.isAnnotationPresent(Inherited.class)) { return predicateAnnotatedWith(annotation); } return new Predicate<Class<?>>() { @Override public boolean apply(Class<?> c) { while (c != null) { if (c.isAnnotationPresent(annotation)) { return true; } c = c.getSuperclass(); } return false; } }; }
/** * An internal-use utility that creates a reified annotation. * This overloaded version take annotation inheritance into account. */ public static <A extends Annotation> A getAnnotation(ClassSymbol annotated, Class<A> annoType) { boolean inherited = annoType.isAnnotationPresent(Inherited.class); A result = null; while (annotated.name != annotated.name.table.names.java_lang_Object) { result = getAnnotation((Symbol)annotated, annoType); if (result != null || !inherited) break; Type sup = annotated.getSuperclass(); if (sup.tag != TypeTags.CLASS || sup.isErroneous()) break; annotated = (ClassSymbol) sup.tsym; } return result; }
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 }
/** * An internal-use utility that creates a reified annotation. * This overloaded version take annotation inheritance into account. */ public static <A extends Annotation> A getAnnotation(ClassSymbol annotated, Class<A> annoType) { boolean inherited = annoType.isAnnotationPresent(Inherited.class); A result = null; while (annotated.name != annotated.name.table.java_lang_Object) { result = getAnnotation((Symbol)annotated, annoType); if (result != null || !inherited) break; Type sup = annotated.getSuperclass(); if (sup.tag != TypeTags.CLASS || sup.isErroneous()) break; annotated = (ClassSymbol) sup.tsym; } return result; }
/** * Index super types for {@link IndexSubclasses} and any {@link IndexAnnotated} * additionally accompanied by {@link Inherited}. */ private void indexSupertypes(TypeElement rootElement, TypeElement element) throws IOException { for (TypeMirror mirror : types.directSupertypes(element.asType())) { if (mirror.getKind() != TypeKind.DECLARED) { continue; } DeclaredType superType = (DeclaredType) mirror; TypeElement superTypeElement = (TypeElement) superType.asElement(); storeSubclass(superTypeElement, rootElement); for (AnnotationMirror annotationMirror : superTypeElement.getAnnotationMirrors()) { TypeElement annotationElement = (TypeElement) annotationMirror.getAnnotationType() .asElement(); if (hasAnnotation(annotationElement, Inherited.class)) { storeAnnotation(annotationElement, rootElement); } } indexSupertypes(rootElement, superTypeElement); } }
@Nonnull @Override public List<String> apply(@Nonnull AnalysisContext analysisContext) { List<String> inheritedAnnotations = newArrayList(); ClassPool classPool = classPoolAccessorFor(analysisContext).getClassPool(); for (String annotation : getAnnotationsFoundInClassPath(analysisContext)) { CtClass annotationClazz = classPool.getOrNull(annotation); if (annotationClazz == null) { logger.debug("Annotation [{}] cannot be found on the class path; skipping detection", annotation); continue; } try { if (annotationClazz.getAnnotation(Inherited.class) != null) { inheritedAnnotations.add(annotation); } } catch (ClassNotFoundException e) { logger.debug("@Inherited is not available; this is quite disturbing."); } } logger.debug("Found those inheritable annotations: {}", inheritedAnnotations); return inheritedAnnotations; }
private static Set<org.kie.soup.project.datamodel.oracle.Annotation> getAnnotations( final java.lang.annotation.Annotation[] annotations, boolean checkInheritance ) { final Set<org.kie.soup.project.datamodel.oracle.Annotation> fieldAnnotations = new LinkedHashSet<>(); for ( java.lang.annotation.Annotation a : annotations ) { if ( checkInheritance ) { if ( !a.annotationType().isAnnotationPresent( Inherited.class ) ) { continue; } } final org.kie.soup.project.datamodel.oracle.Annotation fieldAnnotation = new org.kie.soup.project.datamodel.oracle.Annotation( a.annotationType().getName() ); for ( Method m : a.annotationType().getDeclaredMethods() ) { final String methodName = m.getName(); fieldAnnotation.addParameter( methodName, getAnnotationAttributeValue( a, methodName ) ); } fieldAnnotations.add( fieldAnnotation ); } return fieldAnnotations; }
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(), "<init>", methodDescriptor, false); methodVisitor.visitInsn(Opcodes.RETURN); methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); }
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(); } }
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.", annotationClass), retentionPolicy); assertEquals( rootLocaleFormat("%s must have RUNTIME RetentionPolicy.", annotationClass), RetentionPolicy.RUNTIME, retentionPolicy.value()); assertNotNull( rootLocaleFormat("%s must be inherited.", annotationClass), 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.", annotationClass, propertyName), returnType.isArray()); assertSame(rootLocaleFormat("%s.%s() must return an array of %s.", annotationClass, propertyName, annotationClass.getDeclaringClass()), annotationClass.getDeclaringClass(), returnType.getComponentType()); } }
@Override protected <A extends Annotation> Attribute.Compound getAttribute(final Class<A> annoType) { Attribute.Compound attrib = super.getAttribute(annoType); boolean inherited = annoType.isAnnotationPresent(Inherited.class); if (attrib != null || !inherited) return attrib; // Search supertypes ClassSymbol superType = getSuperClassToSearchForAnnotations(); return superType == null ? null : superType.getAttribute(annoType); }
private void initializeAnnotations() { if (lazyAnnotations != null) { return; } if (parent != null) { lazyAnnotations = new HashMap<Class<?>, Annotation>(); // ((Annotations)parent).initializeAnnotations(); // for (Entry<Class<?>, Annotation> entry : // ((Annotations)parent).lazyAnnotations.entrySet()) { // if // (entry.getValue().annotationType().isAnnotationPresent(Inherited.class)) // { // lazyAnnotations.put(entry.getKey(), entry.getValue()); // } // } for (Annotation a : parent.getAnnotations()) { if (ClassHelper.AsClass(a.annotationType()) .isAnnotationPresent(Inherited.class)) { lazyAnnotations.put(a.annotationType(), a); } } lazyAnnotations.putAll(declaredAnnotations); } else { lazyAnnotations = declaredAnnotations; } }
private static void assertGoodTesterAnnotation( Class<? extends Annotation> annotationClass) { assertNotNull( String.format("%s must be annotated with @TesterAnnotation.", annotationClass), annotationClass.getAnnotation(TesterAnnotation.class)); final Retention retentionPolicy = annotationClass.getAnnotation(Retention.class); assertNotNull( String.format("%s must have a @Retention annotation.", annotationClass), retentionPolicy); assertEquals( String.format("%s must have RUNTIME RetentionPolicy.", annotationClass), RetentionPolicy.RUNTIME, retentionPolicy.value()); assertNotNull( String.format("%s must be inherited.", annotationClass), annotationClass.getAnnotation(Inherited.class)); for (String propertyName : new String[]{"value", "absent"}) { Method method = null; try { method = annotationClass.getMethod(propertyName); } catch (NoSuchMethodException e) { fail(String.format("%s must have a property named '%s'.", annotationClass, propertyName)); } final Class<?> returnType = method.getReturnType(); assertTrue(String.format("%s.%s() must return an array.", annotationClass, propertyName), returnType.isArray()); assertSame(String.format("%s.%s() must return an array of %s.", annotationClass, propertyName, annotationClass.getDeclaringClass()), annotationClass.getDeclaringClass(), returnType.getComponentType()); } }
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(); }
/** * {@inheritDoc} * Overridden here to handle @Inherited. */ public <A extends Annotation> A getAnnotation(Class<A> annoType) { boolean inherited = annoType.isAnnotationPresent(Inherited.class); for (Type t = sym.type; t.tsym != env.symtab.objectType.tsym && !t.isErroneous(); t = env.jctypes.supertype(t)) { A result = getAnnotation(annoType, t.tsym); if (result != null || !inherited) { return result; } } return null; }
/** * Returns all the annotations of this class. If there are no annotations * then an empty array is returned. * * @return a copy of the array containing this class' annotations. * @see #getDeclaredAnnotations() */ public Annotation[] getAnnotations() { /* * We need to get the annotations declared on this class, plus the * annotations from superclasses that have the "@Inherited" annotation * set. We create a temporary map to use while we accumulate the * annotations and convert it to an array at the end. * * It's possible to have duplicates when annotations are inherited. * We use a Map to filter those out. * * HashMap might be overkill here. */ HashMap<Class, Annotation> map = new HashMap<Class, Annotation>(); Annotation[] annos = getDeclaredAnnotations(); for (int i = annos.length-1; i >= 0; --i) map.put(annos[i].annotationType(), annos[i]); for (Class sup = getSuperclass(); sup != null; sup = sup.getSuperclass()) { annos = sup.getDeclaredAnnotations(); for (int i = annos.length-1; i >= 0; --i) { Class clazz = annos[i].annotationType(); if (!map.containsKey(clazz) && clazz.isAnnotationPresent(Inherited.class)) { map.put(clazz, annos[i]); } } } /* convert annotation values from HashMap to array */ Collection<Annotation> coll = map.values(); return coll.toArray(new Annotation[coll.size()]); }
@Override public <A extends Annotation> A getAnnotation(Class<A> annotationClass) { A annotation = _env.getFactory().getAnnotation(getPackedAnnotationBindings(), annotationClass); if (annotation != null || this.getKind() != ElementKind.CLASS || annotationClass.getAnnotation(Inherited.class) == null) return annotation; ElementImpl superClass = (ElementImpl) _env.getFactory().newElement(((ReferenceBinding) this._binding).superclass()); return superClass == null ? null : superClass.getAnnotation(annotationClass); }
public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationType) { A [] annotations = _env.getFactory().getAnnotationsByType(Factory.getUnpackedAnnotationBindings(getPackedAnnotationBindings()), annotationType); if (annotations.length != 0 || this.getKind() != ElementKind.CLASS || annotationType.getAnnotation(Inherited.class) == null) return annotations; ElementImpl superClass = (ElementImpl) _env.getFactory().newElement(((ReferenceBinding) this._binding).superclass()); return superClass == null ? annotations : superClass.getAnnotationsByType(annotationType); }
private AnnotationType(final Class<?> annoCls) { if (!annoCls.isAnnotation()) { throw new IllegalArgumentException("Not an annotation type"); } Method[] methods = annoCls.getDeclaredMethods(); for (Method m : methods) { if (m.getParameterTypes().length == 0) { // cache name -> method assoc String mname = m.getName(); members.put(mname, m); // cache member type Class<?> type = m.getReturnType(); memberTypes.put(mname, invocationHandlerReturnType(type)); // cache member default val (if any) Object val = m.getDefaultValue(); if (val != null) { memberDefaults.put(mname, val); } } else { // probably an exception } } if ((annoCls != Retention.class) && (annoCls != Inherited.class)) { // don't get recursive inherited = annoCls.isAnnotationPresent(Inherited.class); Retention r = annoCls.getAnnotation(Retention.class); if (r == null) { retention = RetentionPolicy.CLASS; } else { retention = r.value(); } } SharedSecrets.getJavaLangAccess().setAnnotationType(annoCls, this); }
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.", annotationClass), retentionPolicy); assertEquals( rootLocaleFormat("%s must have RUNTIME RetentionPolicy.", annotationClass), RetentionPolicy.RUNTIME, retentionPolicy.value()); assertNotNull( rootLocaleFormat("%s must be inherited.", annotationClass), 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.", annotationClass, propertyName), returnType.isArray()); assertSame( rootLocaleFormat( "%s.%s() must return an array of %s.", annotationClass, propertyName, annotationClass.getDeclaringClass()), annotationClass.getDeclaringClass(), returnType.getComponentType()); } }
/** * Execute the supplied runnable once (in same thread) if the supplied method has the supplied annotation. * This method supports inheritance of method annotations. If the supplied method overrides a superclass or * implements an interface with the annotation the runnable will be executed. Even if the annotation is available * from multiple levels of the class hierarchy the runnable will only execute once. * * @param meth The method to test * @param r The runnable that will run depending on the annotation * @param runIfPresent true to run when the annotation is found, false to run when it's not found. * @param annotation The annotation we are looking for */ public void runIfMethodAnnotated(Method meth, Runnable r, boolean runIfPresent, Class<? extends Annotation> annotation) { if (!annotation.isAnnotationPresent(Inherited.class)) { boolean annotationPresent = meth.isAnnotationPresent(annotation); if (runIfPresent && annotationPresent || !runIfPresent && !annotationPresent) { r.run(); } } else { Set<Class> classes = new HashSet<>(); Class<?> clazz = meth.getDeclaringClass(); collectInterfaces(classes, clazz); while (clazz != Object.class) { classes.add(clazz); clazz = clazz.getSuperclass(); } // now iterate all superclasses and interfaces looking for a method with identical signature that has // the annotation in question. boolean found = false; for (Class<?> c : classes) { try { Method m = c.getMethod(meth.getName(), meth.getParameterTypes()); Annotation[] declaredAnnotations = m.getDeclaredAnnotations(); for (Annotation a : declaredAnnotations) { found |= annotation == a.annotationType(); if (runIfPresent && found) { r.run(); return; } } } catch (NoSuchMethodException ignored) { } } if (!runIfPresent && !found) { r.run(); } } }