Java Code Examples for org.springframework.util.ReflectionUtils#getField()

The following examples show how to use org.springframework.util.ReflectionUtils#getField() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SpringMethodRule.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Throw an {@link IllegalStateException} if the supplied {@code testClass}
 * does not declare a {@code public static final SpringClassRule} field
 * that is annotated with {@code @ClassRule}.
 */
private static SpringClassRule validateSpringClassRuleConfiguration(Class<?> testClass) {
	Field ruleField = null;

	for (Field field : testClass.getFields()) {
		if (ReflectionUtils.isPublicStaticFinal(field) && SpringClassRule.class.isAssignableFrom(field.getType())) {
			ruleField = field;
			break;
		}
	}

	if (ruleField == null) {
		throw new IllegalStateException(String.format(
				"Failed to find 'public static final SpringClassRule' field in test class [%s]. " +
				"Consult the javadoc for SpringClassRule for details.", testClass.getName()));
	}

	if (!ruleField.isAnnotationPresent(ClassRule.class)) {
		throw new IllegalStateException(String.format(
				"SpringClassRule field [%s] must be annotated with JUnit's @ClassRule annotation. " +
				"Consult the javadoc for SpringClassRule for details.", ruleField));
	}

	return (SpringClassRule) ReflectionUtils.getField(ruleField, null);
}
 
Example 2
Source File: TaskBatchExecutionListenerFactoryBean.java    From spring-cloud-task with Apache License 2.0 6 votes vote down vote up
private MapTaskBatchDao getMapTaskBatchDao() throws Exception {
	Field taskExecutionDaoField = ReflectionUtils.findField(SimpleTaskExplorer.class,
			"taskExecutionDao");
	taskExecutionDaoField.setAccessible(true);

	MapTaskExecutionDao taskExecutionDao;

	if (AopUtils.isJdkDynamicProxy(this.taskExplorer)) {
		SimpleTaskExplorer dereferencedTaskRepository = (SimpleTaskExplorer) ((Advised) this.taskExplorer)
				.getTargetSource().getTarget();

		taskExecutionDao = (MapTaskExecutionDao) ReflectionUtils
				.getField(taskExecutionDaoField, dereferencedTaskRepository);
	}
	else {
		taskExecutionDao = (MapTaskExecutionDao) ReflectionUtils
				.getField(taskExecutionDaoField, this.taskExplorer);
	}

	return new MapTaskBatchDao(taskExecutionDao.getBatchJobAssociations());
}
 
Example 3
Source File: DefaultObjectDirectoryMapper.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Override
public Name getCalculatedId(Object entry) {
    Assert.notNull(entry, "Entry must not be null");
    EntityData entityData = getEntityData(entry.getClass());
    if(entityData.metaData.canCalculateDn()) {
        Set<AttributeMetaData> dnAttributes = entityData.metaData.getDnAttributes();
        LdapNameBuilder ldapNameBuilder = LdapNameBuilder.newInstance(entityData.metaData.getBase());

        for (AttributeMetaData dnAttribute : dnAttributes) {
            Object dnFieldValue = ReflectionUtils.getField(dnAttribute.getField(), entry);
            if(dnFieldValue == null) {
                throw new IllegalStateException(
                        String.format("DnAttribute for field %s on class %s is null; cannot build DN",
                                dnAttribute.getField().getName(), entry.getClass().getName()));
            }

            ldapNameBuilder.add(dnAttribute.getDnAttribute().value(), dnFieldValue.toString());
        }

        return ldapNameBuilder.build();
    }

    return null;
}
 
Example 4
Source File: CustomPartitionedProducerTest.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomPartitionedProducerAsSingletons() {
	ApplicationContext context = SpringApplication.run(
			CustomPartitionedProducerTest.TestSource.class,
			"--spring.jmx.enabled=false", "--spring.main.web-application-type=none",
			"--spring.cloud.stream.default-binder=mock");
	Source testSource = context.getBean(Source.class);
	DirectChannel messageChannel = (DirectChannel) testSource.output();
	for (ChannelInterceptor channelInterceptor : messageChannel
			.getInterceptors()) {
		if (channelInterceptor instanceof MessageConverterConfigurer.PartitioningInterceptor) {
			Field partitionHandlerField = ReflectionUtils.findField(
					MessageConverterConfigurer.PartitioningInterceptor.class,
					"partitionHandler");
			ReflectionUtils.makeAccessible(partitionHandlerField);
			PartitionHandler partitionHandler = (PartitionHandler) ReflectionUtils
					.getField(partitionHandlerField, channelInterceptor);
			Field partitonKeyExtractorField = ReflectionUtils.findField(
					PartitionHandler.class, "partitionKeyExtractorStrategy");
			ReflectionUtils.makeAccessible(partitonKeyExtractorField);
			Field partitonSelectorField = ReflectionUtils
					.findField(PartitionHandler.class, "partitionSelectorStrategy");
			ReflectionUtils.makeAccessible(partitonSelectorField);
			assertThat(((PartitionKeyExtractorStrategy) ReflectionUtils
					.getField(partitonKeyExtractorField, partitionHandler)).getClass()
							.equals(CustomPartitionKeyExtractorClass.class)).isTrue();
			assertThat(((PartitionSelectorStrategy) ReflectionUtils
					.getField(partitonSelectorField, partitionHandler)).getClass()
							.equals(CustomPartitionSelectorClass.class)).isTrue();
		}
	}
}
 
Example 5
Source File: RefreshEndpointTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
private int countShutdownHooks() {
	Class<?> type = ClassUtils.resolveClassName("java.lang.ApplicationShutdownHooks",
			null);
	Field field = ReflectionUtils.findField(type, "hooks");
	ReflectionUtils.makeAccessible(field);
	@SuppressWarnings("rawtypes")
	Map map = (Map) ReflectionUtils.getField(field, null);
	return map.size();
}
 
Example 6
Source File: UUIDPolicy.java    From bdf3 with Apache License 2.0 5 votes vote down vote up
@Override
protected Object getValue(Object entity, Field field) {
	Object value = ReflectionUtils.getField(field, entity);
	if (value == null) {
		return UUID.randomUUID().toString();
	}
	return value;
}
 
Example 7
Source File: TaskBatchEventListenerBeanPostProcessor.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
		throws BeansException {

	registerJobExecutionEventListener(bean);

	if (bean instanceof AbstractStep) {
		registerStepExecutionEventListener(bean);
		if (bean instanceof TaskletStep) {
			TaskletStep taskletStep = (TaskletStep) bean;
			Tasklet tasklet = taskletStep.getTasklet();
			registerChunkEventsListener(bean);

			if (tasklet instanceof ChunkOrientedTasklet) {
				Field chunkProviderField = ReflectionUtils
						.findField(ChunkOrientedTasklet.class, "chunkProvider");
				ReflectionUtils.makeAccessible(chunkProviderField);
				SimpleChunkProvider chunkProvider = (SimpleChunkProvider) ReflectionUtils
						.getField(chunkProviderField, tasklet);
				Field chunkProcessorField = ReflectionUtils
						.findField(ChunkOrientedTasklet.class, "chunkProcessor");
				ReflectionUtils.makeAccessible(chunkProcessorField);
				SimpleChunkProcessor chunkProcessor = (SimpleChunkProcessor) ReflectionUtils
						.getField(chunkProcessorField, tasklet);
				registerItemReadEvents(chunkProvider);
				registerSkipEvents(chunkProvider);
				registerItemProcessEvents(chunkProcessor);
				registerItemWriteEvents(chunkProcessor);
				registerSkipEvents(chunkProcessor);
			}
		}
	}

	return bean;
}
 
Example 8
Source File: ConfigPropertySourcesProcessorHelperTest.java    From apollo with Apache License 2.0 5 votes vote down vote up
@Test
public void testHelperLoadingOrder() {
  ConfigPropertySourcesProcessor processor = new ConfigPropertySourcesProcessor();

  Field field = ReflectionUtils.findField(ConfigPropertySourcesProcessor.class, "helper");
  ReflectionUtils.makeAccessible(field);
  Object helper = ReflectionUtils.getField(field, processor);

  assertEquals("helper is not TestProcessorHelper instance", TestProcessorHelper.class, helper.getClass());
}
 
Example 9
Source File: RabbitChannelDefinitionProcessor.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void unregisterChannelModel(ChannelModel channelModel, String tenantId, EventRepositoryService eventRepositoryService) {
    String endpointId = getEndpointId(channelModel, tenantId);
    // currently it is not possible to unregister a listener container
    // In order not to do a lot of the logic that Spring does we are manually accessing the containers to remove them
    // see https://github.com/spring-projects/spring-framework/issues/24228
    MessageListenerContainer listenerContainer = endpointRegistry.getListenerContainer(endpointId);
    if (listenerContainer != null) {
        listenerContainer.stop();
    }

    if (listenerContainer instanceof DisposableBean) {
        try {
            ((DisposableBean) listenerContainer).destroy();
        } catch (Exception e) {
            throw new RuntimeException("Failed to destroy listener container", e);
        }
    }

    Field listenerContainersField = ReflectionUtils.findField(endpointRegistry.getClass(), "listenerContainers");
    if (listenerContainersField != null) {
        listenerContainersField.setAccessible(true);
        @SuppressWarnings("unchecked")
        Map<String, MessageListenerContainer> listenerContainers = (Map<String, MessageListenerContainer>) ReflectionUtils
            .getField(listenerContainersField, endpointRegistry);
        if (listenerContainers != null) {
            listenerContainers.remove(endpointId);
        }
    } else {
        throw new IllegalStateException("Endpoint registry " + endpointRegistry + " does not have listenerContainers field");
    }
}
 
Example 10
Source File: ZooKeeperx.java    From canal-1.1.3 with Apache License 2.0 5 votes vote down vote up
public void configMutliCluster(ZooKeeper zk) {
    if (_serversList.size() == 1) {
        return;
    }
    String cluster1 = _serversList.get(0);
    try {
        if (_serversList.size() > 1) {
            // 强制的声明accessible
            ReflectionUtils.makeAccessible(clientCnxnField);
            ReflectionUtils.makeAccessible(hostProviderField);
            ReflectionUtils.makeAccessible(serverAddressesField);

            // 添加第二组集群列表
            for (int i = 1; i < _serversList.size(); i++) {
                String cluster = _serversList.get(i);
                // 强制获取zk中的地址信息
                ClientCnxn cnxn = (ClientCnxn) ReflectionUtils.getField(clientCnxnField, zk);
                HostProvider hostProvider = (HostProvider) ReflectionUtils.getField(hostProviderField, cnxn);
                List<InetSocketAddress> serverAddrs = (List<InetSocketAddress>) ReflectionUtils.getField(serverAddressesField,
                    hostProvider);
                // 添加第二组集群列表
                serverAddrs.addAll(new ConnectStringParser(cluster).getServerAddresses());
            }
        }
    } catch (Exception e) {
        try {
            if (zk != null) {
                zk.close();
            }
        } catch (InterruptedException ie) {
            // ignore interrupt
        }
        throw new ZkException("zookeeper_create_error, serveraddrs=" + cluster1, e);
    }

}
 
Example 11
Source File: ProcessLauncherState.java    From spring-init with Apache License 2.0 5 votes vote down vote up
public String getPid() {
	String pid = null;
	try {
		if (started != null) {
			Field field = ReflectionUtils.findField(started.getClass(), "pid");
			ReflectionUtils.makeAccessible(field);
			pid = "" + ReflectionUtils.getField(field, started);
		}
	}
	catch (Exception e) {
	}
	return pid;
}
 
Example 12
Source File: DataRedisContextInitializer.java    From summerframework with Apache License 2.0 5 votes vote down vote up
private void createProxyHandler(RedisTemplate redisTemplate, Class clazz, String name) {
    try {
        Field field = ReflectionUtils.findField(RedisTemplate.class, name, clazz);
        ReflectionUtils.makeAccessible(field);
        Object object = ReflectionUtils.getField(field, redisTemplate);
        DataRedisProxyHandler handler = new DataRedisProxyHandler(object);
        Object proxy = Proxy.newProxyInstance(handler.getClass().getClassLoader(), new Class[] {clazz}, handler);
        field.set(redisTemplate, proxy);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 13
Source File: JmsChannelModelProcessor.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void unregisterChannelModel(ChannelModel channelModel, String tenantId, EventRepositoryService eventRepositoryService) {
    String endpointId = getEndpointId(channelModel,tenantId);
    // currently it is not possible to unregister a listener container
    // In order not to do a lot of the logic that Spring does we are manually accessing the containers to remove them
    // see https://github.com/spring-projects/spring-framework/issues/24228
    MessageListenerContainer listenerContainer = endpointRegistry.getListenerContainer(endpointId);
    if (listenerContainer != null) {
        listenerContainer.stop();
    }

    if (listenerContainer instanceof DisposableBean) {
        try {
            ((DisposableBean) listenerContainer).destroy();
        } catch (Exception e) {
            throw new RuntimeException("Failed to destroy listener container", e);
        }
    }

    Field listenerContainersField = ReflectionUtils.findField(endpointRegistry.getClass(), "listenerContainers");
    if (listenerContainersField != null) {
        listenerContainersField.setAccessible(true);
        @SuppressWarnings("unchecked")
        Map<String, MessageListenerContainer> listenerContainers = (Map<String, MessageListenerContainer>) ReflectionUtils.getField(listenerContainersField, endpointRegistry);
        if (listenerContainers != null) {
            listenerContainers.remove(endpointId);
        }
    } else {
        throw new IllegalStateException("Endpoint registry " + endpointRegistry + " does not have listenerContainers field");
    }
}
 
Example 14
Source File: CustomPartitionedProducerTest.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
public void testCustomPartitionedProducerMultipleInstances() {
	ApplicationContext context = SpringApplication.run(
			CustomPartitionedProducerTest.TestSourceMultipleStrategies.class,
			"--spring.jmx.enabled=false", "--spring.main.web-application-type=none",
			"--spring.cloud.stream.bindings.output.producer.partitionKeyExtractorName=customPartitionKeyExtractorOne",
			"--spring.cloud.stream.bindings.output.producer.partitionSelectorName=customPartitionSelectorTwo",
			"--spring.cloud.stream.default-binder=mock");
	Source testSource = context.getBean(Source.class);
	DirectChannel messageChannel = (DirectChannel) testSource.output();
	for (ChannelInterceptor channelInterceptor : messageChannel
			.getInterceptors()) {
		if (channelInterceptor instanceof MessageConverterConfigurer.PartitioningInterceptor) {
			Field partitionHandlerField = ReflectionUtils.findField(
					MessageConverterConfigurer.PartitioningInterceptor.class,
					"partitionHandler");
			ReflectionUtils.makeAccessible(partitionHandlerField);
			PartitionHandler partitionHandler = (PartitionHandler) ReflectionUtils
					.getField(partitionHandlerField, channelInterceptor);
			Field partitonKeyExtractorField = ReflectionUtils.findField(
					PartitionHandler.class, "partitionKeyExtractorStrategy");
			ReflectionUtils.makeAccessible(partitonKeyExtractorField);
			Field partitonSelectorField = ReflectionUtils
					.findField(PartitionHandler.class, "partitionSelectorStrategy");
			ReflectionUtils.makeAccessible(partitonSelectorField);
			assertThat(((PartitionKeyExtractorStrategy) ReflectionUtils
					.getField(partitonKeyExtractorField, partitionHandler)).getClass()
							.equals(CustomPartitionKeyExtractorClass.class)).isTrue();
			assertThat(((PartitionSelectorStrategy) ReflectionUtils
					.getField(partitonSelectorField, partitionHandler)).getClass()
							.equals(CustomPartitionSelectorClass.class)).isTrue();
		}
	}
}
 
Example 15
Source File: ConfigurationClassEnhancer.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private ConfigurableBeanFactory getBeanFactory(Object enhancedConfigInstance) {
	Field field = ReflectionUtils.findField(enhancedConfigInstance.getClass(), BEAN_FACTORY_FIELD);
	Assert.state(field != null, "Unable to find generated bean factory field");
	Object beanFactory = ReflectionUtils.getField(field, enhancedConfigInstance);
	Assert.state(beanFactory != null, "BeanFactory has not been injected into @Configuration class");
	Assert.state(beanFactory instanceof ConfigurableBeanFactory,
			"Injected BeanFactory is not a ConfigurableBeanFactory");
	return (ConfigurableBeanFactory) beanFactory;
}
 
Example 16
Source File: CompositeMessageConverterFactory.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
/**
 * @param customConverters a list of {@link AbstractMessageConverter}
 * @param objectMapper object mapper for for serialization / deserialization
 */
public CompositeMessageConverterFactory(
		List<? extends MessageConverter> customConverters,
		ObjectMapper objectMapper) {
	this.objectMapper = objectMapper;
	if (!CollectionUtils.isEmpty(customConverters)) {
		this.converters = new ArrayList<>(customConverters);
	}
	else {
		this.converters = new ArrayList<>();
	}
	initDefaultConverters();

	Field headersField = ReflectionUtils.findField(MessageHeaders.class, "headers");
	headersField.setAccessible(true);
	DefaultContentTypeResolver resolver = new DefaultContentTypeResolver() {
		@Override
		@SuppressWarnings("unchecked")
		public MimeType resolve(@Nullable MessageHeaders headers) {
			Object contentType = headers.get(MessageHeaders.CONTENT_TYPE);
			if (contentType instanceof byte[]) {
				contentType = new String((byte[]) contentType, StandardCharsets.UTF_8);
				contentType = ((String) contentType).replace("\"", "");
				Map<String, Object> headersMap = (Map<String, Object>) ReflectionUtils.getField(headersField, headers);
				headersMap.put(MessageHeaders.CONTENT_TYPE, contentType);
			}
			return super.resolve(headers);
		}
	};
	resolver.setDefaultMimeType(BindingProperties.DEFAULT_CONTENT_TYPE);
	this.converters.stream().filter(mc -> mc instanceof AbstractMessageConverter)
			.forEach(mc -> ((AbstractMessageConverter) mc)
					.setContentTypeResolver(resolver));
}
 
Example 17
Source File: CosmosEntityInformation.java    From spring-data-cosmosdb with MIT License 4 votes vote down vote up
public String getPartitionKeyFieldValue(T entity) {
    return partitionKeyField == null ? null : (String) ReflectionUtils.getField(partitionKeyField, entity);
}
 
Example 18
Source File: AopProxyUtils.java    From phone with Apache License 2.0 4 votes vote down vote up
private static ProxyFactory findJdkDynamicProxyFactory(final Object proxy) {
    Object jdkDynamicAopProxy = ReflectionUtils.getField(JdkDynamicProxy_h_FIELD, proxy);
    return (ProxyFactory) ReflectionUtils.getField(JdkDynamicAopProxy_advised_FIELD, jdkDynamicAopProxy);
}
 
Example 19
Source File: RouteInformationProvider.java    From gocd with Apache License 2.0 4 votes vote down vote up
private static <T> T getField(Object o, String fieldName) {
    Field field = ReflectionUtils.findField(o.getClass(), fieldName);
    ReflectionUtils.makeAccessible(field);
    return (T) ReflectionUtils.getField(field, o);
}
 
Example 20
Source File: HttpClientConfigurableHttpConnectionFactoryTest.java    From spring-cloud-config with Apache License 2.0 4 votes vote down vote up
private HttpClient getActualHttpClient(HttpConnection actualConnection) {
	Field clientField = ReflectionUtils.findField(actualConnection.getClass(),
			"client");
	ReflectionUtils.makeAccessible(clientField);
	return (HttpClient) ReflectionUtils.getField(clientField, actualConnection);
}