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:br.com.autonomiccs.autonomic.plugin.common.utils.ReflectionUtils.java
/** * It sets the given field with value. If it fails to set a value of declared field and the * {@link IllegalArgumentException} or {@link IllegalAccessException} are thrown, it throws * {@link CloudRuntimeException}/*ww w . j a v a 2 s . c om*/ * * @throws CloudRuntimeException */ public void setFieldIntoObject(Object object, String fieldName, Object value) { Field declaredField = getDeclaredField(object, fieldName); if (declaredField == null) { throw new CloudRuntimeException( String.format("Field [fieldName=%s] does not exists into object [%s].", fieldName, object)); } declaredField.setAccessible(true); try { declaredField.set(object, value); } catch (IllegalArgumentException | IllegalAccessException e) { throw new CloudRuntimeException( String.format("Fail to set field [fieldName=%s] into object [%s] with the value [%s].", fieldName, object, value), e); } }
From source file:fr.mtlx.odm.ClassAssistant.java
public <V> void setProperty(final String propertyName, final T entry, final Collection<V> multipleValues) throws MappingException { @SuppressWarnings("unchecked") Class<T> c = (Class<T>) checkNotNull(entry).getClass(); final AttributeMetadata meta = metadata.getAttributeMetadata(propertyName); if (meta == null) { throw new MappingException(format("propertyName: unknown property %s", propertyName)); }//from w w w .j a v a 2 s.c o m if (!meta.isMultivalued()) { throw new MappingException(format("propertyName: single valued property %s", propertyName)); } final Collection<?> targetValues; targetValues = buildCollection(meta.getCollectionType(), meta.getObjectType(), multipleValues); try { PropertyUtils.setProperty(entry, propertyName, targetValues); } catch (IllegalAccessException | InvocationTargetException e) { throw new MappingException(e); } catch (NoSuchMethodException e) { try { doWithFields(c, (final Field f) -> { boolean secured = !f.isAccessible(); if (secured) { f.setAccessible(true); } f.set(entry, targetValues); if (secured) { f.setAccessible(false); } }, (final Field field) -> { final int modifiers = field.getModifiers(); return !isStatic(modifiers) && (field.getName() == null ? propertyName == null : field.getName().equals(propertyName)); }); } catch (SecurityException | IllegalArgumentException e1) { throw new MappingException(e1); } } }
From source file:nl.surfnet.coin.teams.control.AbstractControllerTest.java
private boolean doAutoWireMock(Object target, Object mock, Class interfaceClass, Field[] fields) throws IllegalAccessException { boolean found = false; for (Field field : fields) { if (field.getType().equals(interfaceClass)) { ReflectionUtils.makeAccessible(field); field.set(target, mock); found = true;/*from w w w .j a v a2 s . c om*/ break; } } return found; }
From source file:com.puppycrawl.tools.checkstyle.checks.SuppressWarningsHolderTest.java
@Test public void testIsSuppressedWithAllArgument() throws Exception { Class<?> entry = Class.forName("com.puppycrawl.tools.checkstyle.checks.SuppressWarningsHolder$Entry"); Constructor<?> entryConstr = entry.getDeclaredConstructor(String.class, int.class, int.class, int.class, int.class); entryConstr.setAccessible(true);/*from w w w . ja va2 s . c om*/ Object entryInstance = entryConstr.newInstance("all", 100, 100, 350, 350); List<Object> entriesList = new ArrayList<>(); entriesList.add(entryInstance); ThreadLocal<?> threadLocal = mock(ThreadLocal.class); PowerMockito.doReturn(entriesList).when(threadLocal, "get"); SuppressWarningsHolder holder = new SuppressWarningsHolder(); Field entries = holder.getClass().getDeclaredField("ENTRIES"); entries.setAccessible(true); entries.set(holder, threadLocal); assertFalse(SuppressWarningsHolder.isSuppressed("SourceName", 100, 10)); assertTrue(SuppressWarningsHolder.isSuppressed("SourceName", 100, 150)); assertTrue(SuppressWarningsHolder.isSuppressed("SourceName", 200, 1)); }
From source file:org.apache.http.hacked.HackedHttpComponentsClientHttpRequestFactory.java
/** * {@inheritDoc}// ww w . j a v a 2s. c o m */ public HackedHttpComponentsClientHttpRequestFactory() { super(); Field declaredField; try { declaredField = HttpComponentsClientHttpRequestFactory.class.getDeclaredField("httpClient"); declaredField.setAccessible(true); HackedDefaultHttpClient hackedDefaultHttpClient = new HackedDefaultHttpClient( getHttpClient().getConnectionManager(), null); declaredField.set(this, hackedDefaultHttpClient); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException(e); } }
From source file:com.qualogy.qafe.business.integration.adapter.MappingAdapter.java
private static Object adaptToJavaObject(String mappingId, String attributeName, Object result, Object valueToAdapt, ClassLoader classLoader) { try {/*from w w w . jav a2 s . c o m*/ if (valueToAdapt != null) { Class resultClazz = classLoader.loadClass(result.getClass().getName()); Field field = resultClazz.getDeclaredField(attributeName); field.setAccessible(true); String fieldName = field.getType().getName(); String valueName = valueToAdapt.getClass().getName(); logger.info(field.getType().getName()); if (!fieldName.equals(valueName)) { if (PredefinedClassTypeConverter.isPredefined(field.getType())) valueToAdapt = PredefinedAdapterFactory.create(field.getType()).convert(valueToAdapt); else throw new IllegalArgumentException("Object passed [" + valueToAdapt + "] cannot be converted to type wanted[" + field.getType() + "] for field[" + field.getName() + "] in adapter[" + mappingId + "]"); } else { if (!PredefinedClassTypeConverter.isPredefined(field.getType())) { Class paramClazz = classLoader.loadClass(fieldName); valueToAdapt = paramClazz.cast(valueToAdapt); } } field.set(result, valueToAdapt); } } catch (IllegalArgumentException e) { throw new UnableToAdaptException( "arg [" + valueToAdapt + "] is illegal for field with name [" + attributeName + "]", e); } catch (SecurityException e) { throw new UnableToAdaptException(e); } catch (IllegalAccessException e) { throw new UnableToAdaptException( "field [" + attributeName + "] does not accessible on class [" + result.getClass() + "]", e); } catch (NoSuchFieldException e) { logger.log(Level.WARNING, "field [" + attributeName + "] does not exist on class [" + result.getClass() + "]", e); } catch (ClassNotFoundException e) { throw new UnableToAdaptException( "field [" + attributeName + "] class not found [" + result.getClass() + "]", e); } return result; }
From source file:de.csdev.ebus.command.datatypes.EBusAbstractType.java
/** * Sets a property to a type instance//w w w . j av a 2 s . c om * * @param instance * @param property * @param value */ protected void setInstanceProperty(EBusAbstractType<T> instance, String property, Object value) { if (property.equals("replaceValue")) { if (value instanceof String) { try { instance.setReplaceValue(EBusUtils.toByteArray((String) value)); } catch (EBusTypeException e) { logger.error("error!", e); } } return; } try { Field field = FieldUtils.getField(instance.getClass(), property, true); if (field != null) { field.set(instance, value); } } catch (SecurityException e) { logger.error("error!", e); } catch (IllegalArgumentException e) { logger.error("error!", e); } catch (IllegalAccessException e) { logger.error("error!", e); } }
From source file:in.hatimi.nosh.support.CmdLineManager.java
private boolean injectImpl(Object target, Field field, Object value) { try {/*from w w w . ja v a2 s . c o m*/ boolean accessible = field.isAccessible(); if (!accessible) { field.setAccessible(true); } field.set(target, value); if (!accessible) { field.setAccessible(false); } return true; } catch (Exception exep) { return false; } }
From source file:org.springframework.social.linkedin.api.impl.json.LinkedInNetworkUpdateListDeserializer.java
@Override public LinkedInNetworkUpdate deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new LinkedInModule()); jp.setCodec(mapper);//from www.jav a2 s . co m JsonNode dataNode = jp.readValueAs(JsonNode.class); if (dataNode != null) { LinkedInNetworkUpdate linkedInNetworkUpdate = (LinkedInNetworkUpdate) mapper .reader(new TypeReference<LinkedInNetworkUpdate>() { }).readValue(dataNode); UpdateContent updatedContent = null; UpdateType type = linkedInNetworkUpdate.getUpdateType(); JsonNode updatedNode = dataNode.get("updateContent"); JsonNode person = updatedNode.get("person"); if (type == UpdateType.MSFC) { // Totally different. Looks like a bad API to be honest. person = updatedNode.get("companyPersonUpdate").get("person"); } switch (type) { case CONN: updatedContent = mapper.reader(new TypeReference<UpdateContentConnection>() { }).readValue(person); break; case STAT: updatedContent = mapper.reader(new TypeReference<UpdateContentStatus>() { }).readValue(person); break; case JGRP: updatedContent = mapper.reader(new TypeReference<UpdateContentGroup>() { }).readValue(person); break; case PREC: case SVPR: updatedContent = mapper.reader(new TypeReference<UpdateContentRecommendation>() { }).readValue(person); break; case APPM: updatedContent = mapper.reader(new TypeReference<UpdateContentPersonActivity>() { }).readValue(person); break; case MSFC: updatedContent = mapper.reader(new TypeReference<UpdateContentFollow>() { }).readValue(person); break; case VIRL: updatedContent = mapper.reader(new TypeReference<UpdateContentViral>() { }).readValue(person); break; case SHAR: updatedContent = mapper.reader(new TypeReference<UpdateContentShare>() { }).readValue(person); break; case CMPY: updatedContent = mapper.reader(new TypeReference<UpdateContentCompany>() { }).readValue(updatedNode); break; default: try { updatedContent = mapper.reader(new TypeReference<UpdateContent>() { }).readValue(person); } catch (Exception e) { throw new RuntimeException(e); } } // Need to use reflection to set private updateContent field try { Field f = LinkedInNetworkUpdate.class.getDeclaredField("updateContent"); f.setAccessible(true); f.set(linkedInNetworkUpdate, updatedContent); } catch (Exception e) { throw new RuntimeException(e); } if (type == UpdateType.MSFC) { // Set the action via reflection as it's private String action = updatedNode.get("companyPersonUpdate").get("action").get("code").asText(); try { Field f = UpdateContentFollow.class.getDeclaredField("action"); f.setAccessible(true); f.set(updatedContent, action); } catch (Exception e) { throw new RuntimeException(e); } // Set following via reflection as it's private Company company = mapper.reader(new TypeReference<Company>() { }).readValue(updatedNode.get("company")); try { Field f = UpdateContentFollow.class.getDeclaredField("following"); f.setAccessible(true); f.set(updatedContent, company); } catch (Exception e) { throw new RuntimeException(e); } } else if (type == UpdateType.VIRL) { JsonNode originalUpdate = updatedNode.path("updateAction").path("originalUpdate"); UpdateAction updateAction = mapper.reader(new TypeReference<UpdateAction>() { }).readValue(originalUpdate); String code = updatedNode.path("updateAction").path("action").path("code").textValue(); // Set private immutable field action on updateAction try { Field f = UpdateAction.class.getDeclaredField("action"); f.setAccessible(true); f.set(updateAction, code); } catch (Exception e) { throw new RuntimeException(e); } // Set private immutable field updateAction on updatedContent try { Field f = UpdateContentViral.class.getDeclaredField("updateAction"); f.setAccessible(true); f.set(updatedContent, updateAction); } catch (Exception e) { throw new RuntimeException(e); } } return linkedInNetworkUpdate; } return null; }
From source file:net.mindengine.galen.tests.runner.ReportingTest.java
private void resetUniqueIdForFileTempStorage() throws NoSuchFieldException, IllegalAccessException { Field _uniqueIdField = FileTempStorage.class.getDeclaredField("_uniqueId"); _uniqueIdField.setAccessible(true);/*from w ww . j a v a 2s . co m*/ _uniqueIdField.set(null, 0L); }