Refine search
@Override @SuppressWarnings({"unchecked" }) public void render(HttpRequest request, HttpResponse response, BeanMap beanMap, SpiderBean bean) { Set<Field> requestFields = ReflectionUtils.getAllFields(bean.getClass(), ReflectionUtils.withAnnotation(Request.class)); for(Field field : requestFields) { beanMap.put(field.getName(), request); } }
/** * Registers all available command methods annotated with {@link org.terasology.logic.console.commandSystem.annotations.Command}. */ public static void registerAvailable(Object provider, Console console, Context context) { Predicate<? super Method> predicate = Predicates.<Method>and(ReflectionUtils.withModifier(Modifier.PUBLIC), ReflectionUtils.withAnnotation(Command.class)); Set<Method> commandMethods = ReflectionUtils.getAllMethods(provider.getClass(), predicate); for (Method method : commandMethods) { if (!hasSenderAnnotation(method)) { logger.error("Command {} provided by {} contains a EntityRef without @Sender annotation, may cause a NullPointerException", method.getName(), provider.getClass().getSimpleName()); } logger.debug("Registering command method {} in class {}", method.getName(), method.getDeclaringClass().getCanonicalName()); try { SpecificAccessibleObject<Method> specificMethod = new SpecificAccessibleObject<>(method, provider); MethodCommand command = referringTo(specificMethod, context); console.registerCommand(command); logger.debug("Registered command method {} in class {}", method.getName(), method.getDeclaringClass().getCanonicalName()); } catch (RuntimeException t) { logger.error("Failed to load command method {} in class {}", method.getName(), method.getDeclaringClass().getCanonicalName(), t); } } }
/** * Convert a string cipher name to the integer tag used by GPG * @param cipherName the cipher name * @return integer tag for the cipher */ private static int symmetricKeyAlgorithmNameToTag(String cipherName) { // Use CAST5 if no cipher specified if (StringUtils.isEmpty(cipherName)) { return PGPEncryptedData.CAST5; } Set<Field> fields = ReflectionUtils.getAllFields(PGPEncryptedData.class, ReflectionUtils.withName(cipherName)); if (fields.isEmpty()) { throw new RuntimeException("Could not find tag for cipher name " + cipherName); } try { return fields.iterator().next().getInt(null); } catch (IllegalAccessException e) { throw new RuntimeException("Could not access field " + cipherName, e); } }
/** * get all methods annotated with a given annotation, including annotation member values matching * <p/>depends on MethodAnnotationsScanner configured */ public Set<Method> getMethodsAnnotatedWith(final Annotation annotation) { return filter(getMethodsAnnotatedWith(annotation.annotationType()), withAnnotation(annotation)); }
/** * get all constructors annotated with a given annotation, including annotation member values matching * <p/>depends on MethodAnnotationsScanner configured */ public Set<Constructor> getConstructorsAnnotatedWith(final Annotation annotation) { return filter(getConstructorsAnnotatedWith(annotation.annotationType()), withAnnotation(annotation)); }
/** * get all methods annotated with a given annotation, including annotation member values matching * <p/>depends on FieldAnnotationsScanner configured */ public Set<Field> getFieldsAnnotatedWith(final Annotation annotation) { return filter(getFieldsAnnotatedWith(annotation.annotationType()), withAnnotation(annotation)); }
/** * get types annotated with a given annotation, both classes and annotations, including annotation member values matching * <p>{@link java.lang.annotation.Inherited} is honored according to given honorInherited * <p/>depends on TypeAnnotationsScanner configured */ public Set<Class<?>> getTypesAnnotatedWith(final Annotation annotation, boolean honorInherited) { Iterable<String> annotated = store.get(index(TypeAnnotationsScanner.class), annotation.annotationType().getName()); Iterable<Class<?>> filter = filter(forNames(annotated, loaders()), withAnnotation(annotation)); Iterable<String> classes = getAllAnnotated(names(filter), annotation.annotationType().isAnnotationPresent(Inherited.class), honorInherited); return Sets.newHashSet(concat(filter, forNames(filter(classes, not(in(Sets.newHashSet(annotated)))), loaders()))); }
/** * get types annotated with a given annotation, both classes and annotations * <p>{@link java.lang.annotation.Inherited} is honored according to given honorInherited. * <p>when honoring @Inherited, meta-annotation should only effect annotated super classes and it's sub types * <p>when not honoring @Inherited, meta annotation effects all subtypes, including annotations interfaces and classes * <p><i>Note that this (@Inherited) meta-annotation type has no effect if the annotated type is used for anything other then a class. * Also, this meta-annotation causes annotations to be inherited only from superclasses; annotations on implemented interfaces have no effect.</i> * <p/>depends on TypeAnnotationsScanner and SubTypesScanner configured */ public Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation, boolean honorInherited) { Iterable<String> annotated = store.get(index(TypeAnnotationsScanner.class), annotation.getName()); Iterable<String> classes = getAllAnnotated(annotated, annotation.isAnnotationPresent(Inherited.class), honorInherited); return Sets.newHashSet(concat(forNames(annotated, loaders()), forNames(classes, loaders()))); }
/** * gets all sub types in hierarchy of a given type * <p/>depends on SubTypesScanner configured */ public <T> Set<Class<? extends T>> getSubTypesOf(final Class<T> type) { return Sets.newHashSet(ReflectionUtils.<T>forNames( store.getAll(index(SubTypesScanner.class), Arrays.asList(type.getName())), loaders())); }
/** get all methods of given {@code type}, up the super class hierarchy, optionally filtered by {@code predicates} */ public static Set<Method> getAllMethods(final Class<?> type, Predicate<? super Method>... predicates) { Set<Method> result = Sets.newHashSet(); for (Class<?> t : getAllSuperTypes(type)) { result.addAll(getMethods(t, predicates)); } return result; }
/** get all constructors of given {@code type}, up the super class hierarchy, optionally filtered by {@code predicates} */ public static Set<Constructor> getAllConstructors(final Class<?> type, Predicate<? super Constructor>... predicates) { Set<Constructor> result = Sets.newHashSet(); for (Class<?> t : getAllSuperTypes(type)) { result.addAll(getConstructors(t, predicates)); } return result; }
private static Set<Class<?>> getClasses(ClassLoader classLoader, String packageName) { List<ClassLoader> classLoadersList = new LinkedList<>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); if (classLoader != null) { classLoadersList.add(classLoader); } classLoaders = classLoadersList.toArray(new ClassLoader[0]); FilterBuilder filter = new FilterBuilder() .include(FilterBuilder.prefix(packageName)); if (!isAllowFindingInternalClasses()) { filter.exclude(FilterBuilder.prefix(URM_PACKAGE)); } Reflections reflections = new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner()) .setUrls(ClasspathHelper.forPackage(packageName, classLoaders)) .filterInputsBy(filter) .addClassLoaders(classLoadersList) ); Multimap<String, String> mmap = reflections.getStore().get(SubTypesScanner.class.getSimpleName()); return Sets.newHashSet(ReflectionUtils.forNames(mmap.values(), classLoadersList.toArray(new ClassLoader[0]))); }
Set<Class<? extends T>> scan(Class<? extends T> aClass) { Configuration configuration = ConfigurationBuilder.build((Object[]) packages).addClassLoaders(classLoaders) .addScanners(new AssignableScanner(aClass)); Reflections reflections = new Reflections(configuration); Predicate<Class<? extends T>> classPredicate = klass -> Modifier.isPublic(klass.getModifiers()) && (!klass.isMemberClass() || (klass.isMemberClass() && Modifier .isStatic(klass.getModifiers()))) && !Modifier.isInterface(klass.getModifiers()) && !Modifier.isAbstract(klass.getModifiers()); HashSet<Class<? extends T>> subtypes = Sets.newHashSet( ReflectionUtils.forNames( reflections.getStore() .getAll(AssignableScanner.class.getSimpleName(), Collections.singletonList(aClass.getName())), classLoaders)); return subtypes.stream().filter(classPredicate).collect(Collectors.toSet()); }
Reflections reflections = new Reflections(new ConfigurationBuilder() .setUrls(urls) .filterInputsBy(new FilterBuilder().includePackage(packagesToScan.toArray(new String[packagesToScan.size()]))) types.addAll(ReflectionUtils.forNames(allTypesScanner.types, classLoader));
@Override public Object process(Object object) { for (Field field : getAllFields(object.getClass(), withAnnotation(Inject.class), withType(Registry.class))) { try { field.setAccessible(true); field.set(object, new DefaultRegistry(context)); } catch (Exception e) { throw new RuntimeException(format("Could not inject dependency on field %s of type %s", field.getName(), object.getClass().getName()), e); } } for (Method method : getAllMethods(object.getClass(), withAnnotation(Inject.class), withParameters(Registry.class))) { try { method.invoke(object, new DefaultRegistry(context)); } catch (Exception e) { throw new RuntimeException(format("Could not inject dependency on method %s of type %s", method.getName(), object.getClass().getName()), e); } } return object; } }
public ReflectionProvider(T target, Context context) { try { ReflectFactory reflectFactory = context.get(ReflectFactory.class); CopyStrategyLibrary copyStrategies = context.get(CopyStrategyLibrary.class); ClassMetadata<T, ?> classMetadata = new DefaultClassMetadata<>(new SimpleUri(), (Class<T>) target.getClass(), reflectFactory, copyStrategies); for (Field field : getAllFields(target.getClass(), and(withAnnotation(Range.class), or(withType(Float.TYPE), withType(Float.class))))) { Range range = field.getAnnotation(Range.class); FieldMetadata<T, Float> fieldMetadata = (FieldMetadata<T, Float>) classMetadata.getField(field.getName()); Property property = new FloatProperty(target, fieldMetadata, range.min(), range.max()); properties.add(property); } } catch (NoSuchMethodException e) { logger.error("Cannot provide provide inspection for {}, does not have a default constructor", target.getClass()); } }
@Override public <T> T inject(T object) throws MuleException { for (Field field : getAllFields(object.getClass(), withAnnotation(Inject.class))) { Class<?> dependencyType = field.getType(); for (Method method : getAllMethods(object.getClass(), withAnnotation(Inject.class))) { if (method.getParameters().length == 1) { Class<?> dependencyType = method.getParameterTypes()[0];
public Map<Class<? extends Annotation>, Method> resolve(Class<?> policyClass) { Map<Class<? extends Annotation>, Method> methods = new HashMap<>(); for(Class<? extends Annotation> annot : RESOLVABLE_ANNOTATIONS) { Set<Method> resolved = ReflectionUtils.getMethods( policyClass, withModifier(Modifier.PUBLIC), withAnnotation(annot)); if (! resolved.isEmpty()) { methods.put(annot, resolved.iterator().next()); } } return methods; } }
Set<Method> beforeClassMethods = getAllMethods(testClass, withAnnotation(BeforeClass.class), withReturnType(Void.TYPE), withParametersCount(0), withModifier(Modifier.PUBLIC )); Set<Method> allBeforeClassMethods = getAllMethods(testClass, withAnnotation(BeforeClass.class)); allBeforeClassMethods.removeAll(beforeClassMethods); if (!allBeforeClassMethods.isEmpty()) { Set<Method> afterClassMethods = getAllMethods(testClass, withAnnotation(AfterClass.class), withReturnType(Void.TYPE), withParametersCount(0), withModifier(Modifier.PUBLIC )); Set<Method> allAfterClassMethods = getAllMethods(testClass, withAnnotation(AfterClass.class)); allAfterClassMethods.removeAll(afterClassMethods); if (!allAfterClassMethods.isEmpty()) {
/** * Scans the class this metadata describes, adding all fields to the class' metadata. * * @param copyStrategyLibrary The library of copy strategies * @param factory The reflection provider */ private void addFields(CopyStrategyLibrary copyStrategyLibrary, ReflectFactory factory, Predicate<Field> includedFieldsPredicate) { for (Field field : ReflectionUtils.getAllFields(clazz, includedFieldsPredicate)) { if (Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) { continue; } CopyStrategy<?> copyStrategy = copyStrategyLibrary.getStrategy(field.getGenericType()); try { FIELD metadata = createField(field, copyStrategy, factory); if (metadata != null) { fields.put(metadata.getName().toLowerCase(Locale.ENGLISH), metadata); } } catch (InaccessibleFieldException e) { logger.error("Could not create metadata for field '{}' of type '{}', may be private.'", field, clazz); } } }