@Override public void setApplicationContext(ApplicationContext context) { Field field = ReflectionUtils.findField(Context.class, "applicationContext"); field.setAccessible(true); ReflectionUtils.setField(field, this, context); Field field2 = ReflectionUtils.findField(Context.class, "coreContext"); field2.setAccessible(true); ReflectionUtils.setField(field2, this, context.getParentBeanFactory()); }
public void visit(ASTNode[] nodes, SourceUnit source) { List<ClassNode> classes = source.getAST().getClasses(); AnnotationNode annotation = null; for (ClassNode clazz : classes) { annotation = findAnnotation(clazz); if (annotation != null) { break; } } if (annotation == null) { return; } int[] array = extractLineNumberArray(annotation); if (array != null) { LineNumberVisitor visitor = new LineNumberVisitor(array); for (ClassNode clazz : classes) { visitor.visitClass(clazz); } } String sourceName = extractSourceName(annotation); if (sourceName != null) { source.getAST().setDescription(sourceName); // source.name = sourceName Field field = ReflectionUtils.findField(SourceUnit.class, "name"); field.setAccessible(true); ReflectionUtils.setField(field, source, sourceName); } }
private EventTriggerCaller buildCaller(Class<?> domainClazz, String event) { Method method = ReflectionUtils.findMethod(domainClazz, event); if (method != null) { ReflectionUtils.makeAccessible(method); return new MethodCaller(method); } Field field = ReflectionUtils.findField(domainClazz, event); if (field != null) { ReflectionUtils.makeAccessible(field); return new FieldClosureCaller(field); } MetaMethod metaMethod = domainMetaClass.getMetaMethod(event, EMPTY_OBJECT_ARRAY); if (metaMethod != null) { return new MetaMethodCaller(metaMethod); } MetaProperty metaProperty = domainMetaClass.getMetaProperty(event); if (metaProperty != null) { return new MetaPropertyClosureCaller(metaProperty); } return null; }
/** * Filters non endpoint configuration parameters from parameter list and puts them together as * parameters string. According to given endpoint configuration type only non endpoint * configuration settings are added to parameter string. * * @param parameters * @param endpointConfigurationType * @return */ protected String getParameterString( Map<String, String> parameters, Class<? extends EndpointConfiguration> endpointConfigurationType) { StringBuilder paramString = new StringBuilder(); for (Map.Entry<String, String> parameterEntry : parameters.entrySet()) { Field field = ReflectionUtils.findField(endpointConfigurationType, parameterEntry.getKey()); if (field == null) { if (paramString.length() == 0) { paramString .append("?") .append(parameterEntry.getKey()) .append("=") .append(parameterEntry.getValue()); } else { paramString .append("&") .append(parameterEntry.getKey()) .append("=") .append(parameterEntry.getValue()); } } } return paramString.toString(); }
/* (non-Javadoc) */ @SuppressWarnings("unchecked") private <T> T getFieldValue( final Object source, final String fieldName, final Class<T> targetType) { Field field = ReflectionUtils.findField(source.getClass(), fieldName, targetType); ReflectionUtils.makeAccessible(field); return (T) ReflectionUtils.getField(field, source); }
@Test public void bindsToSpringApplication() throws Exception { // gh-346 this.initializer.setSearchNames("bindtoapplication"); this.initializer.postProcessEnvironment(this.environment, this.application); Field field = ReflectionUtils.findField(SpringApplication.class, "bannerMode"); field.setAccessible(true); assertThat((Banner.Mode) field.get(this.application), equalTo(Banner.Mode.OFF)); }
@Test public void testFeignClientType() throws IllegalAccessException { assertThat(this.feignClient, is(instanceOf(feign.ribbon.RibbonClient.class))); Field field = ReflectionUtils.findField(feign.ribbon.RibbonClient.class, "delegate", Client.class); ReflectionUtils.makeAccessible(field); Client delegate = (Client) field.get(this.feignClient); assertThat(delegate, is(instanceOf(feign.Client.Default.class))); }
@Test public void bindsSystemPropertyToSpringApplication() throws Exception { // gh-951 System.setProperty("spring.main.banner-mode", "off"); this.initializer.postProcessEnvironment(this.environment, this.application); Field field = ReflectionUtils.findField(SpringApplication.class, "bannerMode"); field.setAccessible(true); assertThat((Banner.Mode) field.get(this.application), equalTo(Banner.Mode.OFF)); }
private static Object getField(Object target, String name) { if (target != null) { Field field = ReflectionUtils.findField(target.getClass(), name); if (field != null) { ReflectionUtils.makeAccessible(field); return ReflectionUtils.getField(field, target); } } return null; }
/** * Get a static field value. * * @param clazz The class to check for static property * @param name The field name * @return The value if there is one, or null if unset OR there is no such field */ public static Object getStaticFieldValue(Class<?> clazz, String name) { Field field = ReflectionUtils.findField(clazz, name); if (field != null) { ReflectionUtils.makeAccessible(field); try { return field.get(clazz); } catch (IllegalAccessException ignored) { } } return null; }
@Test public void replacesServiceLocator() throws Exception { SpringApplication application = new SpringApplication(Conf.class); application.setWebEnvironment(false); this.context = application.run(); ServiceLocator instance = ServiceLocator.getInstance(); Field field = ReflectionUtils.findField(ServiceLocator.class, "classResolver"); field.setAccessible(true); Object resolver = field.get(instance); assertThat(resolver).isInstanceOf(SpringPackageScanClassResolver.class); }
protected PreferenceService getPreferenceService() { Field field = ReflectionUtils.findField(super.getClass(), "preferenceService"); ReflectionUtils.makeAccessible(field); try { return (PreferenceService) field.get(this); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
/** * Returns the {@link TypeInformation} for the given atomic field. Will inspect fields first and * return the type of a field if available. Otherwise it will fall back to a {@link * PropertyDescriptor}. * * @param fieldname the fieldname * @return the property information * @see #getGenericType(PropertyDescriptor) */ private TypeInformation<?> getPropertyInformation(String fieldname) { Class<?> type = getType(); Field field = ReflectionUtils.findField(type, fieldname); if (field != null) { return createInfo(field.getGenericType()); } PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(type, fieldname); return descriptor == null ? null : createInfo(getGenericType(descriptor)); }
@SuppressWarnings("unchecked") protected Map<String, List<Resource>> getMappingLocations() throws IllegalAccessException { SimpleUrlHandlerMapping mapping = (SimpleUrlHandlerMapping) this.context.getBean("resourceHandlerMapping"); Field locationsField = ReflectionUtils.findField(ResourceHttpRequestHandler.class, "locations"); locationsField.setAccessible(true); Map<String, List<Resource>> mappingLocations = new LinkedHashMap<String, List<Resource>>(); for (Map.Entry<String, Object> entry : mapping.getHandlerMap().entrySet()) { ResourceHttpRequestHandler handler = (ResourceHttpRequestHandler) entry.getValue(); mappingLocations.put(entry.getKey(), (List<Resource>) locationsField.get(handler)); } return mappingLocations; }
public void testDefaultJarSettings() throws Exception { Properties defaultSettings = bundleCreator.getSettings(); Field field = ReflectionUtils.findField( AbstractConfigurableBundleCreatorTests.class, "jarSettings", Properties.class); ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, null, defaultSettings); assertNotNull(defaultSettings); assertNotNull(bundleCreator.getRootPath()); assertNotNull(bundleCreator.getBundleContentPattern()); assertNotNull(bundleCreator.getManifestLocation()); }
private static Object getField(Object target, String name) { Assert.notNull(target, "Target object must not be null"); Field field = ReflectionUtils.findField(target.getClass(), name); if (field == null) { throw new IllegalArgumentException( "Could not find field [" + name + "] on target [" + target + "]"); } if (logger.isDebugEnabled()) { logger.debug("Getting field [" + name + "] from target [" + target + "]"); } ReflectionUtils.makeAccessible(field); return ReflectionUtils.getField(field, target); }
/** * Removes non config parameters from list of endpoint parameters according to given endpoint * configuration type. All parameters that do not reside to a endpoint configuration setting are * removed so the result is a qualified list of endpoint configuration parameters. * * @param parameters * @param endpointConfigurationType * @return */ protected Map<String, String> getEndpointConfigurationParameters( Map<String, String> parameters, Class<? extends EndpointConfiguration> endpointConfigurationType) { Map<String, String> params = new HashMap<String, String>(); for (Map.Entry<String, String> parameterEntry : parameters.entrySet()) { Field field = ReflectionUtils.findField(endpointConfigurationType, parameterEntry.getKey()); if (field != null) { params.put(parameterEntry.getKey(), parameterEntry.getValue()); } } return params; }
private String toString(DataSource dataSource) { if (dataSource == null) { return "<none>"; } else { try { Field urlField = ReflectionUtils.findField(dataSource.getClass(), "url"); ReflectionUtils.makeAccessible(urlField); return stripCredentials((String) urlField.get(dataSource)); } catch (Exception fe) { try { Method urlMethod = ReflectionUtils.findMethod(dataSource.getClass(), "getUrl"); ReflectionUtils.makeAccessible(urlMethod); return stripCredentials((String) urlMethod.invoke(dataSource, (Object[]) null)); } catch (Exception me) { return "<unknown> " + dataSource.getClass(); } } } }
private void configurePropertyNamingStrategyField( Jackson2ObjectMapperBuilder builder, String fieldName) { // Find the field (this way we automatically support new constants // that may be added by Jackson in the future) Field field = ReflectionUtils.findField( PropertyNamingStrategy.class, fieldName, PropertyNamingStrategy.class); Assert.notNull( field, "Constant named '" + fieldName + "' not found on " + PropertyNamingStrategy.class.getName()); try { builder.propertyNamingStrategy((PropertyNamingStrategy) field.get(null)); } catch (Exception ex) { throw new IllegalStateException(ex); } }
public void setRepositories(Collection<CrudRepository> repositories) { for (CrudRepository repository : repositories) { Class<?> repoClass = AopUtils.getTargetClass(repository); Field infoField = ReflectionUtils.findField(repoClass, "entityInformation"); ReflectionUtils.makeAccessible(infoField); Method m = ReflectionUtils.findMethod(repository.getClass(), "getTargetSource"); ReflectionUtils.makeAccessible(m); try { SingletonTargetSource targetRepo = (SingletonTargetSource) m.invoke(repository); EntityInformation entityInfo = (EntityInformation) infoField.get(targetRepo.getTarget()); Class<?>[] intfs = repository.getClass().getInterfaces(); String name = StringUtils.uncapitalize(intfs[0].getSimpleName().replaceAll("Repository", "")); this.repositories.put( entityInfo.getJavaType(), new RepositoryCacheEntry(name, repository, entityInfo, null)); } catch (Throwable t) { throw new IllegalStateException(t); } } }
/** * Sets properties on endpoint configuration using method reflection. * * @param endpointConfiguration * @param parameters * @param context */ protected void enrichEndpointConfiguration( EndpointConfiguration endpointConfiguration, Map<String, String> parameters, TestContext context) { for (Map.Entry<String, String> parameterEntry : parameters.entrySet()) { Field field = ReflectionUtils.findField(endpointConfiguration.getClass(), parameterEntry.getKey()); if (field == null) { throw new CitrusRuntimeException( String.format( "Unable to find parameter field on endpoint configuration '%s'", parameterEntry.getKey())); } Method setter = ReflectionUtils.findMethod( endpointConfiguration.getClass(), "set" + parameterEntry.getKey().substring(0, 1).toUpperCase() + parameterEntry.getKey().substring(1), field.getType()); if (setter == null) { throw new CitrusRuntimeException( String.format( "Unable to find parameter setter on endpoint configuration '%s'", "set" + parameterEntry.getKey().substring(0, 1).toUpperCase() + parameterEntry.getKey().substring(1))); } ReflectionUtils.invokeMethod( setter, endpointConfiguration, TypeConversionUtils.convertStringToType( parameterEntry.getValue(), field.getType(), context)); } }
@SuppressWarnings("unchecked") public static <T> T getField(Class<?> target, String name) { Field field = ReflectionUtils.findField(target, name, null); ReflectionUtils.makeAccessible(field); return (T) ReflectionUtils.getField(field, target); }
/** * Helper class for generating and exposing metadata for a candidate handler method. The metadata * includes the SpEL expression and the expected payload type. */ private static class HandlerMethod { private static final SpelExpressionParser EXPRESSION_PARSER = new SpelExpressionParser(); private static final ParameterNameDiscoverer PARAMETER_NAME_DISCOVERER = new LocalVariableTableParameterNameDiscoverer(); private static final TypeDescriptor messageTypeDescriptor = TypeDescriptor.valueOf(Message.class); private static final TypeDescriptor messageListTypeDescriptor = new TypeDescriptor(ReflectionUtils.findField(HandlerMethod.class, "dummyMessages")); private static final TypeDescriptor messageArrayTypeDescriptor = TypeDescriptor.valueOf(Message[].class); @SuppressWarnings("unused") private static final Collection<Message<?>> dummyMessages = Collections.emptyList(); private final Method method; private final Expression expression; private final boolean canProcessMessageList; private volatile TypeDescriptor targetParameterTypeDescriptor; private volatile Class<?> targetParameterType = Void.class; private volatile boolean messageMethod; HandlerMethod(Method method, boolean canProcessMessageList) { this.method = method; this.canProcessMessageList = canProcessMessageList; this.expression = this.generateExpression(method); } Expression getExpression() { return this.expression; } Class<?> getTargetParameterType() { return this.targetParameterType; } private boolean isMessageMethod() { return messageMethod; } @Override public String toString() { return this.method.toString(); } private Expression generateExpression(Method method) { StringBuilder sb = new StringBuilder("#target." + method.getName() + "("); Class<?>[] parameterTypes = method.getParameterTypes(); Annotation[][] parameterAnnotations = method.getParameterAnnotations(); boolean hasUnqualifiedMapParameter = false; for (int i = 0; i < parameterTypes.length; i++) { if (i != 0) { sb.append(", "); } MethodParameter methodParameter = new MethodParameter(method, i); TypeDescriptor parameterTypeDescriptor = new TypeDescriptor(methodParameter); Class<?> parameterType = parameterTypeDescriptor.getObjectType(); Annotation mappingAnnotation = findMappingAnnotation(parameterAnnotations[i]); if (mappingAnnotation != null) { Class<? extends Annotation> annotationType = mappingAnnotation.annotationType(); if (annotationType.equals(Payload.class)) { sb.append("payload"); String qualifierExpression = ((Payload) mappingAnnotation).value(); if (StringUtils.hasText(qualifierExpression)) { sb.append("." + qualifierExpression); } if (!StringUtils.hasText(qualifierExpression)) { this.setExclusiveTargetParameterType(parameterTypeDescriptor, methodParameter); } } if (annotationType.equals(Payloads.class)) { sb.append("messages.![payload"); String qualifierExpression = ((Payloads) mappingAnnotation).value(); if (StringUtils.hasText(qualifierExpression)) { sb.append("." + qualifierExpression); } sb.append("]"); if (!StringUtils.hasText(qualifierExpression)) { this.setExclusiveTargetParameterType(parameterTypeDescriptor, methodParameter); } } else if (annotationType.equals(Headers.class)) { Assert.isTrue( Map.class.isAssignableFrom(parameterType), "The @Headers annotation can only be applied to a Map-typed parameter."); sb.append("headers"); } else if (annotationType.equals(Header.class)) { Header headerAnnotation = (Header) mappingAnnotation; sb.append(this.determineHeaderExpression(headerAnnotation, methodParameter)); } } else if (parameterTypeDescriptor.isAssignableTo(messageTypeDescriptor)) { this.messageMethod = true; sb.append("message"); this.setExclusiveTargetParameterType(parameterTypeDescriptor, methodParameter); } else if ((parameterTypeDescriptor.isAssignableTo(messageListTypeDescriptor) || parameterTypeDescriptor.isAssignableTo(messageArrayTypeDescriptor))) { sb.append("messages"); this.setExclusiveTargetParameterType(parameterTypeDescriptor, methodParameter); } else if (Collection.class.isAssignableFrom(parameterType) || parameterType.isArray()) { if (canProcessMessageList) { sb.append("messages.![payload]"); } else { sb.append("payload"); } this.setExclusiveTargetParameterType(parameterTypeDescriptor, methodParameter); } else if (Iterator.class.isAssignableFrom(parameterType)) { if (canProcessMessageList) { Type type = method.getGenericParameterTypes()[i]; Type parameterizedType = null; if (type instanceof ParameterizedType) { parameterizedType = ((ParameterizedType) type).getActualTypeArguments()[0]; if (parameterizedType instanceof ParameterizedType) { parameterizedType = ((ParameterizedType) parameterizedType).getRawType(); } } if (parameterizedType != null && Message.class.isAssignableFrom((Class<?>) parameterizedType)) { sb.append("messages.iterator()"); } else { sb.append("messages.![payload].iterator()"); } } else { sb.append("payload.iterator()"); } this.setExclusiveTargetParameterType(parameterTypeDescriptor, methodParameter); } else if (Map.class.isAssignableFrom(parameterType)) { if (Properties.class.isAssignableFrom(parameterType)) { sb.append( "payload instanceof T(java.util.Map) or " + "(payload instanceof T(String) and payload.contains('=')) ? payload : headers"); } else { sb.append("(payload instanceof T(java.util.Map) ? payload : headers)"); } Assert.isTrue( !hasUnqualifiedMapParameter, "Found more than one Map typed parameter without any qualification. " + "Consider using @Payload or @Headers on at least one of the parameters."); hasUnqualifiedMapParameter = true; } else { sb.append("payload"); this.setExclusiveTargetParameterType(parameterTypeDescriptor, methodParameter); } } if (hasUnqualifiedMapParameter) { if (targetParameterType != null && Map.class.isAssignableFrom(this.targetParameterType)) { throw new IllegalArgumentException( "Unable to determine payload matching parameter due to ambiguous Map typed parameters. " + "Consider adding the @Payload and or @Headers annotations as appropriate."); } } sb.append(")"); if (this.targetParameterTypeDescriptor == null) { this.targetParameterTypeDescriptor = TypeDescriptor.valueOf(Void.class); } return EXPRESSION_PARSER.parseExpression(sb.toString()); } private Annotation findMappingAnnotation(Annotation[] annotations) { if (annotations == null || annotations.length == 0) { return null; } Annotation match = null; for (Annotation annotation : annotations) { Class<? extends Annotation> type = annotation.annotationType(); if (type.equals(Payload.class) || type.equals(Payloads.class) || type.equals(Header.class) || type.equals(Headers.class)) { if (match != null) { throw new MessagingException( "At most one parameter annotation can be provided for message mapping, " + "but found two: [" + match.annotationType().getName() + "] and [" + annotation.annotationType().getName() + "]"); } match = annotation; } } return match; } private String determineHeaderExpression( Header headerAnnotation, MethodParameter methodParameter) { methodParameter.initParameterNameDiscovery(PARAMETER_NAME_DISCOVERER); String headerName = null; String relativeExpression = ""; String valueAttribute = headerAnnotation.value(); if (!StringUtils.hasText(valueAttribute)) { headerName = methodParameter.getParameterName(); } else if (valueAttribute.indexOf('.') != -1) { String tokens[] = valueAttribute.split("\\.", 2); headerName = tokens[0]; if (StringUtils.hasText(tokens[1])) { relativeExpression = "." + tokens[1]; } } else { headerName = valueAttribute; } Assert.notNull( headerName, "Cannot determine header name. Possible reasons: -debug is " + "disabled or header name is not explicitly provided via @Header annotation."); String headerRetrievalExpression = "headers['" + headerName + "']"; String fullHeaderExpression = headerRetrievalExpression + relativeExpression; String fallbackExpression = (headerAnnotation.required()) ? "T(org.springframework.util.Assert).isTrue(false, 'required header not available: " + headerName + "')" : "null"; return headerRetrievalExpression + " != null ? " + fullHeaderExpression + " : " + fallbackExpression; } private synchronized void setExclusiveTargetParameterType( TypeDescriptor targetParameterType, MethodParameter methodParameter) { if (this.targetParameterTypeDescriptor != null) { throw new IneligibleMethodException( "Found more than one parameter type candidate: [" + this.targetParameterTypeDescriptor + "] and [" + targetParameterType + "]"); } this.targetParameterTypeDescriptor = targetParameterType; if (Message.class.isAssignableFrom(targetParameterType.getObjectType())) { methodParameter.increaseNestingLevel(); this.targetParameterType = methodParameter.getNestedParameterType(); methodParameter.decreaseNestingLevel(); } else { this.targetParameterType = targetParameterType.getObjectType(); } } }
@Override public Map<String, Object> findFuzzy( String column, String objectType, String condition, int page, int pageSize) throws ClassNotFoundException, JSONException { String[] columnArray = column.split(","); StringBuffer sbColumn = new StringBuffer(); StringBuffer sbEntity = new StringBuffer(); Map<String, String> aliasMap = new HashMap<String, String>(); for (int i = 0; i < columnArray.length; i++) { if (columnArray[i].indexOf(".") != -1) { String columnHead = columnArray[i].substring(0, columnArray[i].lastIndexOf(".")); String columnBody = columnArray[i].substring(columnArray[i].lastIndexOf(".") + 1); String columnAlias = ""; // Field f = ReflectionUtils.findField(this.getType(objectType), columnHead); Field f = BeanFieldUtil.findField(this.getType(objectType), columnHead); if (null == f) { continue; } if (!aliasMap.containsKey(columnHead)) { columnAlias = "t_" + i; aliasMap.put(columnHead, "t_" + i); sbEntity.append(" left join " + "t_." + columnHead + " as " + "t_" + i); } else { columnAlias = aliasMap.get(columnHead); } sbColumn.append( columnAlias + "." + columnBody + " as " + columnArray[i].replace(".", "_alias_point_") + ","); } else { Field f = ReflectionUtils.findField(this.getType(objectType), columnArray[i]); if (null == f) { continue; } sbColumn.append("t_." + columnArray[i] + " as " + columnArray[i] + ","); } } String sbColumnString = sbColumn.toString(); String hql = "select new map(" + sbColumnString.substring(0, sbColumnString.lastIndexOf(",")) + ") from " + objectType + " as t_ " + sbEntity.toString() + ""; if (condition != null && !condition.equals("")) { String conditionString = ""; JSONObject conditionObject = new JSONObject(condition); System.out.println(conditionObject.keys()); Iterator<String> it = conditionObject.keys(); while (it.hasNext()) { // 遍历 String key = it.next(); String value = conditionObject.getString(key); if (value != null && !value.equals("")) { conditionString += " AND t_." + key + " like '%" + value + "%'"; } } /*String[] conditionArray = condition.split(";"); for (int i = 0; i < conditionArray.length; i++) { String[] cds = conditionArray[i].split("="); if (cds.length > 1 && cds[1] != null && !cds[1].equals("")) { conditionString += "t_."+cds[0] + " like '%" + cds[1] +"%'"; } }*/ if (!conditionString.equals("")) { hql += " where " + conditionString.substring(4); } } System.out.println(hql); return this.commDao.findPageList(page, pageSize, hql); // return this.commDao.findFuzzy(hql, conditionString, page, pageSize); }
static { TableUtils.glazedTableModelSourceField = // ReflectionUtils.findField(GlazedTableModel.class, "source", EventList.class); ReflectionUtils.makeAccessible(TableUtils.glazedTableModelSourceField); }