public EsPropertyNamingStrategy(Class type, Class<? extends EsStore> store) { this.effectiveType = type; for (Field field : ReflectionUtils.getAllFields(type)) { JsonProperty jsonProperty = field.getAnnotation(JsonProperty.class); EsStoreMappingProperty storeSpecificProperty = field.getAnnotation(EsStoreMappingProperty.class); if ((jsonProperty == null && storeSpecificProperty == null) || (storeSpecificProperty != null && storeSpecificProperty.ignore())) { continue; } if (storeSpecificProperty == null || storeSpecificProperty.store() != store) { fieldToJsonMapping.put(jsonProperty.value(), jsonProperty.value()); } else if (storeSpecificProperty.value().indexOf('.') < 0) { fieldToJsonMapping.put(jsonProperty.value(), storeSpecificProperty.value()); } } }
private static<T> List<T> getDeclaredFilters(Class<?> suiteClass, Class<T> returnType) { final Set<Method> methods = ReflectionUtils.getAllMethods(suiteClass, withAnnotation(TestFilterMethod.class), withModifier(Modifier.STATIC), withParametersCount(0), withReturnTypeAssignableTo(returnType)); return methods.stream().flatMap(m -> { try { final T filter = (T) m.invoke(null); if (filter != null) { return Stream.of(filter); } } catch (final Exception ex) { log.warn("Unable to construct test filter ", ex); } return Stream.of(); }).collect(Collectors.toList()); }
@Test public void invokeLambdaFunction_testFunction2_method1() throws Exception { MockHttpServletRequest req = new MockHttpServletRequest(); req.setContent("tempo".getBytes()); MockHttpServletResponse resp = new MockHttpServletResponse(); lambdaLocalServlet.invokeLambdaFunction(req, resp, new LambdaFunction("/testPath2", TestFunction2.class, ReflectionUtils.getMethods(TestFunction2.class, method -> method.getName().equals("method1")).stream() .findFirst() .get(), new StringDeserializer(), new StringSerializer())); assertThat(resp.getContentAsString()).isEqualTo("hello tempo"); }
@Test public void invokeLambdaFunction_testFunction2_method2() throws Exception { MockHttpServletRequest req = new MockHttpServletRequest(); req.setContent("tempo".getBytes()); MockHttpServletResponse resp = new MockHttpServletResponse(); lambdaLocalServlet.invokeLambdaFunction(req, resp, new LambdaFunction("/testPath3", TestFunction2.class, ReflectionUtils.getMethods(TestFunction2.class, method -> method.getName().equals("method2")).stream() .findFirst() .get(), new StringDeserializer(), new StringSerializer())); assertThat(resp.getContentAsString()).isEqualTo("hi tempo"); }
private static ClassViewDescriptor createClassViewDescriptor(final Class<?> dataType) { @SuppressWarnings("unchecked") final Set<Field> fields = ReflectionUtils.getAllFields(dataType, ReflectionUtils.withAnnotations(ViewColumn.class)); final ImmutableList<ClassViewColumnDescriptor> columns = fields.stream() .map(field -> createClassViewColumnDescriptor(field)) .collect(ImmutableList.toImmutableList()); if (columns.isEmpty()) { return ClassViewDescriptor.EMPTY; } return ClassViewDescriptor.builder() // .className(dataType.getName()) .columns(columns) .build(); }
private static WebuiProcessClassInfo createWebuiProcessClassInfo(final Class<?> processClass) throws Exception { final ProcessClassInfo processClassInfo = ProcessClassInfo.of(processClass); final WebuiProcess webuiProcessAnn = processClass.getAnnotation(WebuiProcess.class); @SuppressWarnings("unchecked") final Set<Method> lookupValuesProviderMethods = ReflectionUtils.getAllMethods(processClass, ReflectionUtils.withAnnotation(ProcessParamLookupValuesProvider.class)); final ImmutableMap<String, LookupDescriptorProvider> paramLookupValuesProviders = lookupValuesProviderMethods.stream() .map(method -> createParamLookupValuesProvider(method)) .collect(GuavaCollectors.toImmutableMap()); // // Check is there were no settings at all so we could return our NULL instance if (ProcessClassInfo.isNull(processClassInfo) && paramLookupValuesProviders.isEmpty()) { return NULL; } return new WebuiProcessClassInfo(processClassInfo, webuiProcessAnn, paramLookupValuesProviders); }
private static final ViewActionDescriptorsList createFromClass(@NonNull final Class<?> clazz) { final ActionIdGenerator actionIdGenerator = new ActionIdGenerator(); @SuppressWarnings("unchecked") final Set<Method> viewActionMethods = ReflectionUtils.getAllMethods(clazz, ReflectionUtils.withAnnotation(ViewAction.class)); final List<ViewActionDescriptor> viewActions = viewActionMethods.stream() .map(viewActionMethod -> { try { return createViewActionDescriptor(actionIdGenerator.getActionId(viewActionMethod), viewActionMethod); } catch (final Throwable ex) { logger.warn("Failed creating view action descriptor for {}. Ignored", viewActionMethod, ex); return null; } }) .filter(actionDescriptor -> actionDescriptor != null) .collect(Collectors.toList()); return ViewActionDescriptorsList.of(viewActions); }
/** * Creates a copy of this Rule with a new instance of the generated rule class if present. * * This prevents sharing instances across threads, which is not supported for performance reasons. * Otherwise the generated code would need to be thread safe, adding to the runtime overhead. * Instead we buy speed by spending more memory. * * @param functionRegistry the registered functions of the system * @return a copy of this rule with a new instance of its generated code */ public Rule invokableCopy(FunctionRegistry functionRegistry) { final Builder builder = toBuilder(); final Class<? extends GeneratedRule> ruleClass = generatedRuleClass(); if (ruleClass != null) { try { //noinspection unchecked final Set<Constructor> constructors = ReflectionUtils.getConstructors(ruleClass); final Constructor onlyElement = Iterables.getOnlyElement(constructors); final GeneratedRule instance = (GeneratedRule) onlyElement.newInstance(functionRegistry); builder.generatedRule(instance); } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { LOG.warn("Unable to generate code for rule {}: {}", id(), e); } } return builder.build(); }
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()); }
@SneakyThrows private WebTarget resolveQueryParams(WebTarget target, SchemaLink link, String method) { UriTemplate uriTemplate = link.getHref(); if (method.equalsIgnoreCase("get") && requestObject != null) { List<String> vars = uriTemplate.getTemplateVariables(); Set<Field> matchingFields = ReflectionUtils.getAllFields(requestObject.getClass(), f -> !vars.contains(f.getName())); for (Field field : matchingFields) { field.setAccessible(true); if (field.get(requestObject) != null) { if (Collection.class.isAssignableFrom(field.getType())) { Collection<?> value = (Collection<?>) field.get(requestObject); String[] values = value.stream().map(Object::toString).collect(Collectors.toList()) .toArray(new String[0]); target = target.queryParam(field.getName(), values); } else { target = target.queryParam(field.getName(), field.get(requestObject).toString()); } } } } return target; }
public GraphQLFieldDefinition getFieldDefinition(DfsContext dfsContext, Class<?> implClass, Field field) { GraphQLFieldDefinition graphQLFieldDefinition = null; ResolvableTypeAccessor resolvableTypeAccessor = ResolvableTypeAccessor.forField(field, implClass); if (resolvableTypeAccessor.isNotIgnorable()) { GraphQLOutputType graphQLOutputType = (GraphQLOutputType) createGraphQLFieldType(dfsContext, resolvableTypeAccessor, true); GraphQLFieldDefinition.Builder graphQLFieldDefinitionBuilder = GraphQLFieldDefinition.newFieldDefinition() .name(resolvableTypeAccessor.getName()) .type(graphQLOutputType) .deprecate(resolvableTypeAccessor.getGraphQLDeprecationReason()) .description(resolvableTypeAccessor.getDescription()); boolean isConstant = Modifier.isFinal(field.getModifiers()) && Modifier.isStatic(field.getModifiers()); if (isConstant) { graphQLFieldDefinitionBuilder.staticValue(org.springframework.util.ReflectionUtils.getField(field, null)); } graphQLFieldDefinition = graphQLFieldDefinitionBuilder.build(); addToFieldDefinitionResolverMap(dfsContext, graphQLFieldDefinition, resolvableTypeAccessor.getGraphQLComplexitySpelExpression()); } return graphQLFieldDefinition; }
public Object invokeMethodByName(DfsContext dfsContext, Class<?> implClass, String methodName, Object... args) { Object defaultValue = null; if (StringUtils.hasText(methodName)) { Object object = null; if (getGraphQLSchemaBeanFactory().containsBean(implClass)) object = getGraphQLSchemaBeanFactory().getBeanByType(implClass); Method defaultValueProviderMethod = args == null ? org.springframework.util.ReflectionUtils.findMethod(implClass, methodName) : org.springframework.util.ReflectionUtils.findMethod(implClass, methodName, getArgumentClasses(args)); if (defaultValueProviderMethod != null) { defaultValue = org.springframework.util.ReflectionUtils.invokeMethod(defaultValueProviderMethod, object, args); } } return defaultValue; }
@SuppressWarnings("unchecked") @Override public Set<FlagField<?>> scanAndBind() { Set<FlagField<?>> fields = new HashSet<>(); for (Object obj : objectsToScan) { ReflectionUtils.getAllFields( obj.getClass(), ReflectionUtils.withTypeAssignableTo(Flag.class), ReflectionUtils.withAnnotation(FlagInfo.class), ReflectionUtils.withModifier(Modifier.FINAL), not(ReflectionUtils.withModifier(Modifier.STATIC))) .stream() .map(f -> boundFlagField(f, obj)) .forEach(fields::add); } return fields; }
private Constructor<? extends Resource> lookingForConstructor(Class<? extends Resource> resourceClass) { LOGGER.debug("Looking for a constructor to inject resource configuration"); Constructor <? extends Resource> constructor = null; Set<Constructor> resourceConstructors = ReflectionUtils.getConstructors(resourceClass, withModifier(Modifier.PUBLIC), withParametersAssignableFrom(ResourceConfiguration.class), withParametersCount(1)); if (resourceConstructors.isEmpty()) { LOGGER.debug("No configuration can be injected for {} because there is no valid constructor. " + "Using default empty constructor.", resourceClass.getName()); try { constructor = resourceClass.getConstructor(); } catch (NoSuchMethodException nsme) { LOGGER.error("Unable to find default empty constructor for {}", resourceClass.getName(), nsme); } } else if (resourceConstructors.size() == 1) { constructor = resourceConstructors.iterator().next(); } else { LOGGER.info("Too much constructors to instantiate resource {}", resourceClass.getName()); } return constructor; }
@SuppressWarnings("unchecked") private final Set<String> findDefinedColumnNames() { // // Collect all columnnames final ImmutableSet.Builder<String> columnNamesBuilder = ImmutableSet.builder(); ReflectionUtils.getAllFields(modelClass, new Predicate<Field>() { @Override public boolean apply(final Field field) { final String fieldName = field.getName(); if (fieldName.startsWith("COLUMNNAME_")) { final String columnName = fieldName.substring("COLUMNNAME_".length()); columnNamesBuilder.add(columnName); } return false; } }); return columnNamesBuilder.build(); }
public JavaAssistInterceptorInstance(final Class<? extends Annotation> annotationClass, final Object interceptorImpl) { super(); Check.assumeNotNull(annotationClass, "annotationClass not null"); this.annotationClass = annotationClass; Check.assumeNotNull(interceptorImpl, "interceptorImpl not null"); this.interceptorImpl = interceptorImpl; final Class<? extends Object> interceptorImplClass = interceptorImpl.getClass(); @SuppressWarnings("unchecked") final Set<Method> aroundInvokeMethods = ReflectionUtils.getAllMethods(interceptorImplClass, ReflectionUtils.withAnnotation(AroundInvoke.class)); Check.errorIf(aroundInvokeMethods.size() != 1, "Class {} needs to have exactly one method annotated with @AroundInvoke. It has:{}", interceptorImpl, aroundInvokeMethods); this.aroundInvokeMethod = aroundInvokeMethods.iterator().next(); Check.assumeNotNull(aroundInvokeMethod, "aroundInvokeMethod not null for {}", interceptorImplClass); }
/** * Gets the config and display map. Display map is a mapping from field name to how the field * should be displayed in the UI * @param remoteType The remote type that identifies what plugin to get * @return * @throws IOException */ @SuppressWarnings({ "unchecked" }) @RequestMapping(method = { RequestMethod.GET }, value = "/plugins/remote/cdm/{remoteType}") @ResponseBody public Map<String, Object> getPluginConfigAndDisplayMap(@PathVariable String remoteType) throws IOException { PluginConfiguration config = getRemotePlugin(remoteType); if (config == null) return null; Map<String, String> displayMap = new HashMap<String, String>(); Set<Field> fields = ReflectionUtils.getFields(config.getClass(), ReflectionUtils.withAnnotation(PluginConfigValue.class)); for (Field field : fields) { String disp = field.getAnnotation(PluginConfigValue.class).display(); if (StringUtils.isEmpty(disp)) { disp = field.getName(); } displayMap.put(field.getName(), disp); } Map<String, Object> configAndDM = new HashMap<>(); configAndDM.put("config", config); configAndDM.put("displayMap", displayMap); return configAndDM; }
private Method getAddMethod(Class clazz, TypeToken typeToken, Field field, String javaFieldNameUpperCased, Method getMethod) { Method addMethod = null; if (Collection.class.isAssignableFrom(getMethod.getReturnType())) { Type[] typeArguments = ((ParameterizedType) getMethod.getGenericReturnType()).getActualTypeArguments(); if (typeArguments.length == 1) { TypeToken singularParameter = typeToken.resolveType(typeArguments[0]); //TODO: does this work or should we use the typeArguments[0].getSomething? String addMethodName = "add" + toSingular(javaFieldNameUpperCased); addMethod = getMethod(clazz, addMethodName, singularParameter.getRawType()); if (addMethod == null) { //Due to generics, this does not always work Set<Method> allAddMethods = ReflectionUtils.getAllMethods(clazz, ReflectionUtils.withName(addMethodName)); if (allAddMethods.size() == 1) { addMethod = allAddMethods.iterator().next(); } else { logger.warn("strange number of add methods for field {} on class {}", field.getName(), clazz.getSimpleName()); } } } } return addMethod; }
public String getEventStreamId() { Set<Field> fields = ReflectionUtils.getFields(getClass(), ReflectionUtils.withAnnotation(EventStreamId.class)); if (fields.size() != 1) { throw new RuntimeException( String.format("No aggregate id field found in class %s", getClass())); } Field first = fields.iterator().next(); first.setAccessible(true); try { return (String) first.get(this); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
private void setEventStreamId(T aggregate, String id) { Set<Field> fields = ReflectionUtils.getFields(getAggregateClass(), ReflectionUtils.withAnnotation(EventStreamId.class)); if (fields.size() != 1) { throw new RuntimeException( String.format("No aggregate id field found in class %s", getAggregateClass())); } Field first = fields.iterator().next(); try { first.setAccessible(true); first.set(aggregate, id); } catch (IllegalAccessException e) { throw new RuntimeException( String.format("Could not set aggregate id on class %s", getAggregateClass())); } }
@SuppressWarnings("unchecked") private T createAndReplayAggregate(String eventStreamId, EventStream stream) { Set<Constructor> result = ReflectionUtils.getConstructors(getAggregateClass(), ReflectionUtils.withParameters()); if (result.size() != 1) { throw new DomainEventHandlerException("Only one no-arg constructor allowed for aggregates."); } try { Constructor first = result.iterator().next(); first.setAccessible(true); T object = (T) first.newInstance(); object.replay(stream); setEventStreamId(object, eventStreamId); return object; } catch (Exception e) { throw new DomainEventHandlerException(e); } }
private Method getUpgradeMethod(DomainEvent event) { Class<?> providerClass = eventTypeToProvider.get(event.getClass()).getClass(); Set<Method> methods = ReflectionUtils.getMethods(providerClass, ReflectionUtils.withAnnotation(EventUpgrader.class), ReflectionUtils.withParametersCount(1), ReflectionUtils.withParameters(event.getClass())); if (methods.size() != 1) { throw new RuntimeException( String.format("Duplicate upgrade methods for event type %s in class %s.", event.getClass(), providerClass)); } return methods.stream().findFirst().get(); }
Set<Class<DomainEvent>> supportedDomainEvents(Class<?> upgradeProvider) { Set<Method> methods = ReflectionUtils.getMethods(upgradeProvider, ReflectionUtils.withAnnotation(EventUpgrader.class)); if (methods.isEmpty()) { throw new RuntimeException( String.format("No event eventTypeToProvider found in class %s", upgradeProvider)); } Set<Class<DomainEvent>> result = new HashSet<>(); for (Method method : methods) { if (method.getParameterCount() != 1) { throw new RuntimeException( String.format("Parameter count for upgrade method %s must be exactly one.", method)); } result.add((Class<DomainEvent>) method.getParameters()[0].getType()); } return result; }
/** * Extracts all beans with annotation {@link ImmutableRegistry} from Spring * context and converts all fields with the type {@link Map} to * {@link ImmutableMap}. * * @param context */ @SuppressWarnings("unchecked") public static void invoke(ApplicationContext context) { Collection<Object> registries = context.getBeansWithAnnotation(ImmutableRegistry.class).values(); for (Object registry : registries) { Set<Field> mapFields = ReflectionUtils.getAllFields(registry.getClass(), new AssignableFromPredicate(Map.class)); for (Field mapField : mapFields) { try { mapField.setAccessible(true); Map<?, ?> sourceMap = (Map<?, ?>) mapField.get(registry); if (sourceMap != null && !(sourceMap instanceof ImmutableMap)) { mapField.set(registry, ImmutableMap.copyOf(sourceMap)); log.info("Convert to immutable map: " + registry + " -> " + mapField); } mapField.setAccessible(false); } catch (IllegalArgumentException | IllegalAccessException e) { throw new IllegalStateException(e); } } } }
private Set<Class<?>> getSubtypes(final Class<?> type) throws ComboBoxIsTooFullException { final ClassLoader[] classloaders = new ClassLoader[] { currentModelHandler.getCustomClassLoader(), currentModelHandler.getCustomClassLoader().getParent() }; final ConfigurationBuilder builder = new ConfigurationBuilder(). addUrls(ClasspathHelper.forClassLoader(currentModelHandler.getCustomClassLoader())). addClassLoaders(classloaders). setScanners(new SubTypesScanner(false)); final Reflections ref = new Reflections(builder); final Set<Class<?>> result = new HashSet<Class<?>>(); final Set<String> subTypesStr = ref.getStore().getSubTypesOf(type.getName()); if (subTypesStr.size() > MAX_SIZE_OF_SUBPARAMETER_COMBOBOX) throw new ComboBoxIsTooFullException(); for (final String clsName : subTypesStr) { try { result.add(ReflectionUtils.forName(clsName,classloaders)); } catch (final ReflectionsException e) { // intentionally blank } } return result; }
@Override @SuppressWarnings({ "unchecked" }) public void render(HttpRequest request, HttpResponse response, BeanMap beanMap, SpiderBean bean) { Map<String, Object> fieldMap = new HashMap<String, Object>(); Set<Field> jsonPathFields = ReflectionUtils.getAllFields(bean.getClass(), ReflectionUtils.withAnnotation(JSONPath.class)); String jsonStr = response.getContent(); jsonStr = jsonp2Json(jsonStr); if (jsonStr == null) { return; } try { Object json = JSON.parse(jsonStr); for (Field field : jsonPathFields) { Object value = injectJsonField(request, field, json); if(value != null) { fieldMap.put(field.getName(), value); } } } catch(JSONException ex) { //throw new RenderException(ex.getMessage(), bean.getClass()); RenderException.log("json parse error : " + request.getUrl(), bean.getClass(), ex); } beanMap.putAll(fieldMap); }
private Iterable<? extends Class<? extends Annotation>> getConfiguredCustomAnnotations() { return Iterables.transform(options.getCustomAnnotationClasses(), new Function<String, Class<? extends Annotation>>() { @Override @SuppressWarnings("unchecked") public Class<? extends Annotation> apply(String className) { Class<?> validatorClass = ReflectionUtils.forName(className); if (validatorClass.isAnnotation()) { return (Class<? extends Annotation>) validatorClass; } else { logger.warn("The configured custom annotation class '{}' is not an annotation. It will be ignored.", validatorClass); return null; } } }); }
@SuppressWarnings({ "rawtypes", "unchecked" }) private Method findLifecycleMethod(final Class lifecycleAnnotationClass) { Set<Method> methods = ReflectionUtils.getMethods(declaringClass, new Predicate<Method>() { @Override public boolean apply(Method input) { return input != null && input.getAnnotation(lifecycleAnnotationClass) != null; } }); if (methods.isEmpty()) { return null; } if (methods.size() > 1) { throw new BootstrapException("Found multiple " + lifecycleAnnotationClass.getSimpleName() + " methods in class " + declaringClass.getSimpleName() + ". Only 1 is allowed."); } return methods.iterator().next(); }
@SuppressWarnings("unchecked") private void extractAnyColumn() { Set<Field> anyColumnFields = ReflectionUtils.getAllFields(type, withAnnotation(AnyColumn.class)); if (anyColumnFields.size() > 0) { if (anyColumnFields.size() > 1) { throw new XceliteException("Multiple AnyColumn fields are not allowed"); } Field anyColumnField = anyColumnFields.iterator().next(); if (!anyColumnField.getType().isAssignableFrom(Map.class)) { throw new XceliteException( String.format("AnyColumn field \"%s\" should be of type Map.class or assignable from Map.class", anyColumnField.getName())); } anyColumn = new Col(anyColumnField.getName(), anyColumnField.getName()); anyColumn.setAnyColumn(true); AnyColumn annotation = anyColumnField.getAnnotation(AnyColumn.class); anyColumn.setType(annotation.as()); if (annotation.converter() != NoConverterClass.class) { anyColumn.setConverter(annotation.converter()); } } }
private void initializeInterceptor() { AbstractWebApplication application = (AbstractWebApplication) getApplication(); for (Field field : ReflectionUtils.getAllFields(this.getClass())) { if (field.getAnnotation(Setting.class) != null) { Setting setting = field.getAnnotation(Setting.class); if (field.getType() != FileUpload.class && field.getType() != FileUpload[].class) { try { FieldUtils.writeField( field, this, application.select(setting.name(), field.getType()), true); } catch (IllegalAccessException e) { } } } } org.apache.wicket.markup.html.form.TextField<String> repository = (org.apache.wicket.markup.html.form.TextField<String>) getFormComponent("repository"); getForm().add(new LocalRepositoryValidator(repository)); }
private void initializeInterceptor() { AbstractWebApplication application = (AbstractWebApplication) getApplication(); for (Field field : ReflectionUtils.getAllFields(this.getClass())) { if (field.getAnnotation(Setting.class) != null) { Setting setting = field.getAnnotation(Setting.class); if (field.getType() != FileUpload.class && field.getType() != FileUpload[].class) { try { FieldUtils.writeField( field, this, application.select(setting.name(), field.getType()), true); } catch (IllegalAccessException e) { } } } } org.apache.wicket.markup.html.form.TextField<String> local = (org.apache.wicket.markup.html.form.TextField<String>) getFormComponent("repository"); getForm().add(new LocalRepositoryValidator(local)); }
@SuppressWarnings("unchecked") public GenericEntityMapper(Class<T> clazz) { this.clazz = clazz; if (org.springframework.core.annotation.AnnotationUtils.findAnnotation( this.clazz, Entity.class) == null) { throw new DatabaseException(clazz.getSimpleName() + " is not entity"); } for (Field field : ReflectionUtils.getAllFields(this.clazz)) { Column column = field.getAnnotation(Column.class); if (column != null) { fields.put(column.name(), field.getName()); types.put(field.getName(), field); } } }
private String createLongMessage(String name, String shortMessage, Class<? extends Operation> opClass) { List<Pair<Field, Operand>> operands = ReflectionUtils.getAllFields(opClass, ReflectionUtils.withAnnotation(Operand.class)) .stream() .map(f -> Pair.of(f, f.getAnnotation(Operand.class))) .filter(p -> p.getRight() != null) .sorted((p1, p2) -> Integer.compare(p1.getRight().order(), p2.getRight().order())) .collect(Collectors.toList()); String header = name + " " + operands.stream() .map(p -> getOperandIdentifier(p.getLeft(), p.getRight())) .collect(Collectors.joining(" ")); String operandDescriptions = operands.stream() .map(p -> String.format("%15s -- %s", p.getLeft().getName(), getOperandDescription(p.getLeft()))) .collect(Collectors.joining("\n")); return header + "\n\n" + shortMessage + "\n\n" + operandDescriptions; }
public static Method resolveMethod(final Class aMethod) { String methodOgnl = aMethod.getSimpleName(); try { String methodName; Class<?>[] paramTypes; if (methodOgnl.contains(tokenSeparator)) { methodName = methodOgnl.substring(0, methodOgnl.indexOf(tokenSeparator)); String[] params = methodOgnl.substring(methodOgnl.indexOf(tokenSeparator) + 1).split(doubleSeparator); paramTypes = new Class<?>[params.length]; for (int i = 0; i < params.length; i++) { String typeName = params[i].replace(arrayDescriptor, "[]").replace(pathSeparator, dotSeparator); paramTypes[i] = ReflectionUtils.forName(typeName); } } else { methodName = methodOgnl; paramTypes = null; } Class<?> declaringClass = aMethod.getDeclaringClass().getDeclaringClass(); return resolveClassOf(declaringClass).getDeclaredMethod(methodName, paramTypes); } catch (Exception e) { throw new ReflectionsException("could not resolve to method " + aMethod.getName(), e); } }
/** * Obtain the "completeness" (i.e. "empty", "id and type", "it, type and label", "id only" or "complex") of * a IIIF resource. Can be useful for determining how to serialize the resource, e.g. often resources with only * an id are serialized as a string. * * @param res The IIIF resource to check the completeness of * @param type The type of the IIIF resource * @return The completeness */ public static Completeness getCompleteness(Object res, Class<?> type) { Set<Method> getters = ReflectionUtils.getAllMethods( type, ReflectionUtils.withModifier(Modifier.PUBLIC), ReflectionUtils.withPrefix("get")); Set<String> gettersWithValues = getters.stream() .filter(g -> g.getAnnotation(JsonIgnore.class) == null) // Only JSON-serializable fields .filter(g -> returnsValue(g, res)) .map(Method::getName) .collect(Collectors.toSet()); boolean hasOnlyTypeAndId = ( gettersWithValues.size() == 2 && Stream.of("getType", "getIdentifier").allMatch(gettersWithValues::contains)); if (gettersWithValues.isEmpty()) { return Completeness.EMPTY; } else if (containsOnly(gettersWithValues, "getType", "getIdentifier")) { return Completeness.ID_AND_TYPE; } else if (containsOnly(gettersWithValues, "getType", "getIdentifier", "getLabels")) { return Completeness.ID_AND_TYPE_AND_LABEL; } else if (containsOnly(gettersWithValues, "getIdentifier")) { return Completeness.ID_ONLY; } else { return Completeness.COMPLEX; } }
/** * 获取实体中所有简单的数据库映射字段 */ public static List<String> getSimpleORMFieldInEntity(Class entityClass){ if(entityClass==null){ return null ; } //获取所有声明的字段 Set<Field> fields = ReflectionUtils.getAllFields(entityClass) ; List<String> simpleFields = new ArrayList<String>() ; for (Field field : fields) { if(isSimpleORMField(field)){ simpleFields.add(field.getName()) ; } } return simpleFields ; }
public static Map<String, Field> getAllFields(Class classType) { if (!classAllFieldsCache.containsKey(classType)) { Set<Field> objectFieldsSet = ReflectionUtils.getAllFields(classType); Map<String, Field> objectFieldsMap = new HashMap<>(); for (Field f : objectFieldsSet) { objectFieldsMap.put(f.getName(), f); } classAllFieldsCache.put(classType, objectFieldsMap); } return classAllFieldsCache.get(classType); }
private Class<?> getFollowUpClass(PropertyDescriptor propertyDescriptor, Class<?> clazzBefore) { Class<?> clazz = propertyDescriptor.getElementClass(); if (Collection.class.isAssignableFrom(clazz)) { final Predicate<? super Field> predicate = f -> f.getName().equals(propertyDescriptor .getPropertyName()); @SuppressWarnings("unchecked") Set<Field> field = ReflectionUtils.getAllFields(clazzBefore, predicate); Type typeArgument = ((ParameterizedType) field.iterator().next().getGenericType()) .getActualTypeArguments()[0]; return (Class<?>) typeArgument; } else { return clazz; } }
private Set<Class<?>> typesAnnotatedWith(Reflections reflections, Class<? extends Annotation> annotation) { Set<Class<?>> types = new HashSet<>(); Set<Method> methodsAnnotatedWith; synchronized (ReflectionUtils.class) { methodsAnnotatedWith = reflections .getMethodsAnnotatedWith(annotation); } for (Method method : methodsAnnotatedWith) { types.add(method.getDeclaringClass()); } return types; }
@Override protected void configure() { Set<Field> f = ReflectionUtils.getAllFields(instanceToReadMocksFrom.getClass()); for (Field field : f) { if (field.getAnnotation(Mock.class) != null || field.getAnnotation(Spy.class) != null) { try { field.setAccessible(true); bindReflectedInstance(field.get(instanceToReadMocksFrom), field.getType()); } catch (Exception e) { throw new IllegalArgumentException("Unable to bind mock field " + field.getName() + " from " + instanceToReadMocksFrom.getClass().getName(), e); } } } }