private static void setField(Object target, String name, Object value) { Assert.notNull(target, "Target object must not be null"); Field field = ReflectionUtils.findField(target.getClass(), name); if (field == null) { throw new IllegalStateException("Could not find field [" + name + "] on target [" + target + "]"); } if (logger.isDebugEnabled()) { logger.debug("Getting field [" + name + "] from target [" + target + "]"); } ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, target, value); }
@Override protected void processField(Object bean, String beanName, Field field) { ApolloConfig annotation = AnnotationUtils.getAnnotation(field, ApolloConfig.class); if (annotation == null) { return; } Preconditions.checkArgument(Config.class.isAssignableFrom(field.getType()), "Invalid type: %s for field: %s, should be Config", field.getType(), field); String namespace = annotation.value(); Config config = ConfigService.getConfig(namespace); ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, bean, config); }
ReflectionUtils.setField(field, targetObject, value);
@Override public void connect(Watcher watcher) { ReflectionUtils.makeAccessible(zookeeperLockField); ReflectionUtils.makeAccessible(zookeeperFiled); Lock _zookeeperLock = (ReentrantLock) ReflectionUtils.getField(zookeeperLockField, this); ZooKeeper _zk = (ZooKeeper) ReflectionUtils.getField(zookeeperFiled, this); _zookeeperLock.lock(); try { if (_zk != null) { throw new IllegalStateException("zk client has already been started"); } String zkServers = _serversList.get(0); try { logger.debug("Creating new ZookKeeper instance to connect to " + zkServers + "."); _zk = new ZooKeeper(zkServers, _sessionTimeOut, watcher); configMutliCluster(_zk); ReflectionUtils.setField(zookeeperFiled, this, _zk); } catch (IOException e) { throw new ZkException("Unable to connect to " + zkServers, e); } } finally { _zookeeperLock.unlock(); } }
protected void setFieldValue(String fieldname, Object value, Object object) { Field f = ReflectionUtils.findField(object.getClass(), fieldname); ReflectionUtils.makeAccessible(f); ReflectionUtils.setField(f, object, value); }
@Override protected void processField(Object bean, String beanName, Field field) { ApolloJsonValue apolloJsonValue = AnnotationUtils.getAnnotation(field, ApolloJsonValue.class); if (apolloJsonValue == null) { return; } String placeholder = apolloJsonValue.value(); Object propertyValue = placeholderHelper .resolvePropertyValue(beanFactory, beanName, placeholder); // propertyValue will never be null, as @ApolloJsonValue will not allow that if (!(propertyValue instanceof String)) { return; } boolean accessible = field.isAccessible(); field.setAccessible(true); ReflectionUtils .setField(field, bean, parseJsonValue((String)propertyValue, field.getGenericType())); field.setAccessible(accessible); if (configUtil.isAutoUpdateInjectedSpringPropertiesEnabled()) { Set<String> keys = placeholderHelper.extractPlaceholderKeys(placeholder); for (String key : keys) { SpringValue springValue = new SpringValue(key, placeholder, bean, beanName, field, true); springValueRegistry.register(beanFactory, key, springValue); logger.debug("Monitoring {}", springValue); } } }
private SqlSessionFactory buildSqlSessionFactory() throws IOException { SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder(); Configuration baseConfiguration = new XMLConfigBuilder(configLocation.getInputStream()).parse(); String ibatisConfigXmlLocation = databaseStrategy.getIbatisConfigXmlLocation(); if (isNotBlank(ibatisConfigXmlLocation)) { XMLConfigBuilder builder = new XMLConfigBuilder(new ClassPathResource(ibatisConfigXmlLocation).getInputStream()); // hacky way to "inject" a previous configuration Field configurationField = ReflectionUtils.findField(XMLConfigBuilder.class, "configuration"); ReflectionUtils.makeAccessible(configurationField); ReflectionUtils.setField(configurationField, builder, baseConfiguration); baseConfiguration = builder.parse(); } baseConfiguration.setEnvironment(new Environment(getClass().getSimpleName(), new SpringManagedTransactionFactory(), this.dataSource)); return factoryBuilder.build(baseConfiguration); }
@Test public void setField() { TestObjectSubclassWithNewField testBean = new TestObjectSubclassWithNewField(); Field field = ReflectionUtils.findField(TestObjectSubclassWithNewField.class, "name", String.class); ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, testBean, "FooBar"); assertNotNull(testBean.getName()); assertEquals("FooBar", testBean.getName()); ReflectionUtils.setField(field, testBean, null); assertNull(testBean.getName()); }
/** * Sets the {@code value} into the {@code target} instance * * @param target the object on which the field value is to be set * @param value the value to set */ public void set(Target target, Value value) { ReflectionUtils.setField(field, target, value); }
private void recoverThreadLocal(Field field, Thread caller, Thread runner) { if (runner == null) { return; } // 清理runner线程的ThreadLocal,为下一个task服务 ReflectionUtils.setField(field, runner, null); }
@SuppressWarnings("unchecked") public static void resetConfig() { ReflectionUtils.setField(FIELD_INSTANCE, null, null); ReflectionUtils.setField(FIELD_CUSTOM_CONFIGURATION_INSTALLED, null, false); ReflectionUtils.setField(FIELD_CONFIG, null, null); ReflectionUtils.setField(FIELD_INITIALIZED_WITH_DEFAULT_CONFIG, null, false); ReflectionUtils.setField(FIELD_DYNAMIC_PROPERTY_SUPPORTIMPL, null, null); ((ConcurrentHashMap<String, DynamicProperty>) ReflectionUtils.getField(FIELD_DYNAMIC_PROPERTY_ALL_PROPS, null)) .clear(); }
private static void injectValueIntoField(ValueProvider fieldContainer, Object valueToInject, Field field) { field.setAccessible(true); org.springframework.util.ReflectionUtils.setField(field, fieldContainer, valueToInject); } }
@Override public void set(Object target, ResolverSetResult result) throws MuleException { container.setAccessible(true); ParameterGroupObjectBuilder<?> parameterGroupObjectBuilder = new ParameterGroupObjectBuilder<>(groupDescriptor, reflectionCache.get(), expressionManager.get()); setField(container, target, parameterGroupObjectBuilder.build(result)); } }
public VertxImplEx(String name, VertxOptions vertxOptions) { super(vertxOptions); if (StringUtils.isEmpty(name)) { return; } Field field = ReflectionUtils.findField(VertxImpl.class, "eventLoopThreadFactory"); field.setAccessible(true); VertxThreadFactory eventLoopThreadFactory = (VertxThreadFactory) ReflectionUtils.getField(field, this); field = ReflectionUtils.findField(eventLoopThreadFactory.getClass(), "prefix"); field.setAccessible(true); String prefix = (String) ReflectionUtils.getField(field, eventLoopThreadFactory); ReflectionUtils.setField(field, eventLoopThreadFactory, name + "-" + prefix); }
private void initThreadLocal(Field field, Thread caller, Thread runner) { if (caller == null || runner == null) { return; } // 主要考虑这样的情况: // 1. // 如果caller线程没有使用ThreadLocal对象,而异步加载的runner线程执行中使用了ThreadLocal对象,则需要复制对象到caller线程上 // 2. // 后续caller,多个runner线程有使用ThreadLocal对象,使用的是同一个引用,直接set都是针对同一个ThreadLocal,所以以后就不需要进行合并 // 因为在提交Runnable时已经同步创建了一个ThreadLocalMap对象,所以runner线程只需要复制caller对应的引用即可,不需要进行合并,简化处理 // threadlocal属性复制,注意是引用复制 Object callerThreadLocalMap = ReflectionUtils.getField(field, caller); if (callerThreadLocalMap != null) { ReflectionUtils.setField(field, runner, callerThreadLocalMap);// 复制caller的信息到runner线程上 } else { // 这个分支不会出现,因为在execute提交的时候已经添加 } }
private void removeObjenesisCache(Class<?> dummyInvocationUtils) { try { Field objenesisField = ReflectionUtils.findField(dummyInvocationUtils, "OBJENESIS"); if (objenesisField != null) { ReflectionUtils.makeAccessible(objenesisField); Object objenesis = ReflectionUtils.getField(objenesisField, null); Field cacheField = ReflectionUtils.findField(objenesis.getClass(), "cache"); ReflectionUtils.makeAccessible(cacheField); ReflectionUtils.setField(cacheField, objenesis, null); } } catch (Exception ex) { logger.warn( "Failed to disable Spring HATEOAS's Objenesis cache. ClassCastExceptions may occur", ex); } }
@Override public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException { Class<?> clazz = bean.getClass(); do { for (final Field field : clazz.getDeclaredFields()) { GrpcClient annotation = AnnotationUtils.findAnnotation(field, GrpcClient.class); if (annotation != null) { ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, bean, processInjectionPoint(field, field.getType(), annotation)); } } for (final Method method : clazz.getDeclaredMethods()) { GrpcClient annotation = AnnotationUtils.findAnnotation(method, GrpcClient.class); if (annotation != null) { Class<?>[] paramTypes = method.getParameterTypes(); if (paramTypes.length != 1) { throw new BeanDefinitionStoreException( "Method " + method + " doesn't have exactly one parameter."); } ReflectionUtils.makeAccessible(method); ReflectionUtils.invokeMethod(method, bean, processInjectionPoint(method, paramTypes[0], annotation)); } } clazz = clazz.getSuperclass(); } while (clazz != null); return bean; }
private void handleReferenceField(Object obj, Field field, RpcReference reference) { String microserviceName = reference.microserviceName(); microserviceName = resolver.resolveStringValue(microserviceName); PojoReferenceMeta pojoReference = new PojoReferenceMeta(); pojoReference.setMicroserviceName(microserviceName); pojoReference.setSchemaId(reference.schemaId()); pojoReference.setConsumerIntf(field.getType()); pojoReference.afterPropertiesSet(); ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, obj, pojoReference.getProxy()); } }
@Test public void testInboundAdapterUsageWithHeaderMapper() throws Exception { XMPPConnection xmppConnection = Mockito.mock(XMPPConnection.class); ChatMessageListeningEndpoint adapter = context.getBean("xmppInboundAdapter", ChatMessageListeningEndpoint.class); Field xmppConnectionField = ReflectionUtils.findField(ChatMessageListeningEndpoint.class, "xmppConnection"); xmppConnectionField.setAccessible(true); ReflectionUtils.setField(xmppConnectionField, adapter, xmppConnection); StanzaListener stanzaListener = TestUtils.getPropertyValue(adapter, "stanzaListener", StanzaListener.class); Message message = new Message(); message.setBody("hello"); message.setTo(JidCreate.from("oleg")); JivePropertiesManager.addProperty(message, "foo", "foo"); JivePropertiesManager.addProperty(message, "bar", "bar"); stanzaListener.processStanza(message); org.springframework.messaging.Message<?> siMessage = xmppInbound.receive(0); assertEquals("foo", siMessage.getHeaders().get("foo")); assertEquals("oleg", siMessage.getHeaders().get("xmpp_to")); }
@Test @Ignore public void performanceTest() { int times = 1000000; StopWatch watch = new StopWatch(); watch.start(); for (int i = 0; i < times; i++) { new GenericMessage<Integer>(0); } watch.stop(); double defaultGeneratorElapsedTime = watch.getTotalTimeSeconds(); Field idGeneratorField = ReflectionUtils.findField(MessageHeaders.class, "idGenerator"); ReflectionUtils.makeAccessible(idGeneratorField); ReflectionUtils.setField(idGeneratorField, null, (IdGenerator) () -> TimeBasedUUIDGenerator.generateId()); watch = new StopWatch(); watch.start(); for (int i = 0; i < times; i++) { new GenericMessage<Integer>(0); } watch.stop(); double timebasedGeneratorElapsedTime = watch.getTotalTimeSeconds(); logger.info("Generated " + times + " messages using default UUID generator " + "in " + defaultGeneratorElapsedTime + " seconds"); logger.info("Generated " + times + " messages using Timebased UUID generator " + "in " + timebasedGeneratorElapsedTime + " seconds"); logger.info("Time-based ID generator is " + defaultGeneratorElapsedTime / timebasedGeneratorElapsedTime + " times faster"); }