List of usage examples for java.lang.reflect Field set
@CallerSensitive @ForceInline public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException
From source file:com.linkedin.pinot.transport.common.routing.RandomRoutingTableTest.java
@Test public void testHelixExternalViewBasedRoutingTable() throws Exception { String tableName = "testTable_OFFLINE"; String fileName = RandomRoutingTableTest.class.getClassLoader().getResource("SampleExternalView.json") .getFile();//from www . j a v a 2s .c om System.out.println(fileName); InputStream evInputStream = new FileInputStream(fileName); ZNRecordSerializer znRecordSerializer = new ZNRecordSerializer(); ZNRecord externalViewRecord = (ZNRecord) znRecordSerializer.deserialize(IOUtils.toByteArray(evInputStream)); int totalRuns = 10000; RoutingTableBuilder routingStrategy = new BalancedRandomRoutingTableBuilder(10); HelixExternalViewBasedRouting routingTable = new HelixExternalViewBasedRouting(null, null); Field offlineRTBField = HelixExternalViewBasedRouting.class.getDeclaredField("_offlineRoutingTableBuilder"); offlineRTBField.setAccessible(true); offlineRTBField.set(routingTable, routingStrategy); ExternalView externalView = new ExternalView(externalViewRecord); routingTable.markDataResourceOnline(tableName, externalView, getInstanceConfigs(externalView)); double[] globalArrays = new double[9]; for (int numRun = 0; numRun < totalRuns; ++numRun) { RoutingTableLookupRequest request = new RoutingTableLookupRequest(tableName); Map<ServerInstance, SegmentIdSet> serversMap = routingTable.findServers(request); TreeSet<ServerInstance> serverInstances = new TreeSet<ServerInstance>(serversMap.keySet()); int i = 0; double[] arrays = new double[9]; for (ServerInstance serverInstance : serverInstances) { globalArrays[i] += serversMap.get(serverInstance).getSegments().size(); arrays[i++] = serversMap.get(serverInstance).getSegments().size(); } for (int j = 0; i < arrays.length; ++j) { Assert.assertTrue(arrays[j] / totalRuns <= 31); Assert.assertTrue(arrays[j] / totalRuns >= 28); } //System.out.println(Arrays.toString(arrays) + " : " + new StandardDeviation().evaluate(arrays) + " : " + new Mean().evaluate(arrays)); } for (int i = 0; i < globalArrays.length; ++i) { Assert.assertTrue(globalArrays[i] / totalRuns <= 31); Assert.assertTrue(globalArrays[i] / totalRuns >= 28); } System.out.println(Arrays.toString(globalArrays) + " : " + new StandardDeviation().evaluate(globalArrays) + " : " + new Mean().evaluate(globalArrays)); }
From source file:com.thoughtworks.xstream.benchmark.reflection.targets.AbstractReflectionTarget.java
protected void fill(final Object o) { final char[] zero = new char[8]; Arrays.fill(zero, '0'); for (Class cls = o.getClass(); cls != Object.class; cls = cls.getSuperclass()) { final Field[] fields = cls.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { final Field field = fields[i]; field.setAccessible(true);//from www. ja v a 2s. c o m if (field.getType() == String.class) { final String hex = Integer.toHexString(i); try { field.set(o, new String(zero, 0, zero.length - hex.length()) + hex); } catch (final IllegalAccessException e) { throw new RuntimeException(e); } } } } }
From source file:com.android.tests.lib.LibUnitTest.java
@Test public void instanceFields() throws Exception { SyncResult result = mock(SyncResult.class); Field statsField = result.getClass().getField("stats"); SyncStats syncStats = mock(SyncStats.class); statsField.set(result, syncStats); syncStats.numDeletes = 42;//w w w. ja v a2 s.c o m assertEquals(42, result.stats.numDeletes); }
From source file:com.gargoylesoftware.htmlunit.runners.FrameworkMethodWithParameters.java
/** * {@inheritDoc}//from ww w. j av a2 s. com */ @Override public Object invokeExplosively(final Object target, final Object... params) throws Throwable { if (!parameters_.isEmpty()) { final List<FrameworkField> annotatedFieldsByParameter = testClass_.getAnnotatedFields(Parameter.class); if (annotatedFieldsByParameter.size() != parameters_.size()) { throw new Exception("Wrong number of parameters and @Parameter fields." + " @Parameter fields counted: " + annotatedFieldsByParameter.size() + ", available parameters: " + parameters_.size() + "."); } for (final FrameworkField each : annotatedFieldsByParameter) { final Field field = each.getField(); final Parameter annotation = field.getAnnotation(Parameter.class); final int index = annotation.value(); try { field.set(target, parameters_.get(index)); } catch (final IllegalArgumentException iare) { throw new Exception(testClass_.getName() + ": Trying to set " + field.getName() + " with the value " + parameters_.get(index) + " that is not the right type (" + parameters_.get(index).getClass().getSimpleName() + " instead of " + field.getType().getSimpleName() + ").", iare); } } } return super.invokeExplosively(target, params); }
From source file:com.liferay.portal.template.velocity.internal.LiferayResourceManager.java
@Override public synchronized void initialize(RuntimeServices runtimeServices) throws Exception { ExtendedProperties extendedProperties = runtimeServices.getConfiguration(); Field field = ReflectionUtil.getDeclaredField(RuntimeInstance.class, "configuration"); field.set(runtimeServices, new FastExtendedProperties(extendedProperties)); _macroTemplateIds = StringPlus.asList(extendedProperties.get(VelocityEngine.VM_LIBRARY)); _resourceModificationCheckInterval = GetterUtil.getInteger(extendedProperties .get("liferay." + VelocityEngine.RESOURCE_LOADER + ".resourceModificationCheckInterval"), 60); _templateResourceLoader = (TemplateResourceLoader) extendedProperties .get(VelocityTemplateResourceLoader.class.getName()); super.initialize(runtimeServices); }
From source file:org.brekka.stillingar.spring.pc.ConstructorArgDefChangeListener.java
@Override protected void onChange(String newValue) { ConfigurableListableBeanFactory beanFactory = beanFactoryRef.get(); if (beanFactory == null) { return;/*from w w w. j ava 2s . c o m*/ } BeanDefinition beanDef = beanFactory.getMergedBeanDefinition(beanName); ConstructorArgumentValues mutableConstructorValues = beanDef.getConstructorArgumentValues(); ValueHolder valueHolder = null; List<ValueHolder> genericArgumentValues = mutableConstructorValues.getGenericArgumentValues(); if (constructorArgIndex != null) { valueHolder = mutableConstructorValues.getIndexedArgumentValues().get(constructorArgIndex); if (valueHolder == null) { throw new IllegalStateException( String.format("Failed to find constructor arg at index %d", constructorArgIndex)); } } else if (genericArgumentValues.size() == 1) { valueHolder = genericArgumentValues.get(0); } else { for (ValueHolder vh : genericArgumentValues) { if (vh.getType().equals(constructorArgType)) { valueHolder = vh; } } if (valueHolder == null) { throw new IllegalStateException( String.format("Failed to find constructor arg with type '%s'", constructorArgType)); } } if (!ObjectUtils.nullSafeEquals(newValue, valueHolder.getValue())) { valueHolder.setValue(newValue); try { /* * Spring implements caching of constructor values, which can be reset by clearing the package-private * field 'resolvedConstructorOrFactoryMethod' on RootBeanDefinition. Naturally this will fail if a * security manager is present but there doesn't seem to be any other way to do it. Make sure to warn * about this in the documentation! */ Field field = beanDef.getClass().getDeclaredField("resolvedConstructorOrFactoryMethod"); field.setAccessible(true); field.set(beanDef, null); } catch (Exception e) { throw new ConfigurationException(String.format( "Unable to update value for constructor argument '%s'. " + "Failed to reset the cached constructor state for bean '%s'", (constructorArgIndex != null ? constructorArgIndex.toString() : constructorArgType), beanName), e); } } }
From source file:co.cask.cdap.file.dropzone.FileDropZoneIT.java
@Test public void fileDropZoneBasicIT() throws Exception { final File configurationFile = getConfigFile(); PollingServiceManager pollingServiceManager = new PollingServiceManager(configurationFile); pollingServiceManager.initManager(); Field monitor = pollingServiceManager.getClass().getDeclaredField("monitor"); monitor.setAccessible(true);//from www . ja v a 2 s . co m PollingService myMonitor = (PollingService) monitor.get(pollingServiceManager); ObserverConfiguration observerConf = loadConfig(configurationFile); PollingListener myPollingListener = new PollingListenerImpl(myMonitor, observerConf); FileTailerMetricsProcessor metricsProcessor = getMetricsProcessor(observerConf); Field metricsProcessorField = myPollingListener.getClass().getDeclaredField("metricsProcessor"); metricsProcessorField.setAccessible(true); metricsProcessorField.set(myPollingListener, metricsProcessor); myMonitor.registerDirMonitor(observerConf.getPipeConf().getSourceConfiguration().getWorkDir(), myPollingListener); createFile(observerConf.getPipeConf().getSourceConfiguration().getWorkDir().getAbsolutePath()); pollingServiceManager.startMonitor(); Thread.sleep(SLEEP_TIME); pollingServiceManager.stopMonitor(); Assert.assertEquals(read.get(), ingest.get()); }
From source file:almira.sample.util.LogPostProcessor.java
@Override public Object postProcessBeforeInitialization(final Object bean, String beanName) { ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() { @Override// w w w. jav a 2s. com public void doWith(Field field) throws IllegalAccessException { ReflectionUtils.makeAccessible(field); if (field.getAnnotation(Log.class) != null) { Logger logger = LoggerFactory.getLogger(bean.getClass().getName()); field.set(bean, logger); } } }); return bean; }
From source file:com.ngandroid.lib.NgAndroid.java
public <T> T buildModel(Object scope, String fieldName, Class<T> clss) { try {//ww w .j a v a 2 s . co m Field f = scope.getClass().getDeclaredField(fieldName); f.setAccessible(true); T val = (T) new ModelBuilder(clss).create(); f.set(scope, val); return val; } catch (NoSuchFieldException e) { //TODO throw new RuntimeException( "There is no such field '" + fieldName + "' found in " + scope.getClass().getSimpleName()); } catch (IllegalAccessException e) { throw new RuntimeException( "Unable to access field '" + fieldName + "' in " + scope.getClass().getSimpleName()); } }
From source file:jp.terasoluna.fw.beans.jxpath.JXPATH152PatchActivatorTest.java
/** * ??// w ww . j a v a 2s . c om * @throws Exception ????? */ @After public void tearDown() throws Exception { logger.clear(); Field field = JXPathIntrospector.class.getDeclaredField("byClass"); field.setAccessible(true); field.set(JXPathIntrospector.class, byClassBak); field = JXPathIntrospector.class.getDeclaredField("byInterface"); field.setAccessible(true); field.set(JXPathIntrospector.class, byInterfaceBak); }