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:net.sourceforge.stripes.integration.spring.SpringHelper.java
/** * Looks for all methods and fields annotated with {@code @SpringBean} and attempts * to lookup and inject a managed bean into the field/property. If any annotated * element cannot be injected an exception is thrown. * * @param bean the bean into which to inject spring beans * @param ctx the Spring application context *///w w w .ja v a 2s .co m public static void injectBeans(Object bean, ApplicationContext ctx) { // First inject any values using annotated methods for (Method m : getMethods(bean.getClass())) { try { SpringBean springBean = m.getAnnotation(SpringBean.class); boolean nameSupplied = !"".equals(springBean.value()); String name = nameSupplied ? springBean.value() : methodToPropertyName(m); Class<?> beanType = m.getParameterTypes()[0]; Object managedBean = findSpringBean(ctx, name, beanType, !nameSupplied); m.invoke(bean, managedBean); } catch (Exception e) { throw new StripesRuntimeException( "Exception while trying to lookup and inject " + "a Spring bean into a bean of type " + bean.getClass().getSimpleName() + " using method " + m.toString(), e); } } // And then inject any properties that are annotated for (Field f : getFields(bean.getClass())) { try { SpringBean springBean = f.getAnnotation(SpringBean.class); boolean nameSupplied = !"".equals(springBean.value()); String name = nameSupplied ? springBean.value() : f.getName(); Object managedBean = findSpringBean(ctx, name, f.getType(), !nameSupplied); f.set(bean, managedBean); } catch (Exception e) { throw new StripesRuntimeException( "Exception while trying to lookup and inject " + "a Spring bean into a bean of type " + bean.getClass().getSimpleName() + " using field access on field " + f.toString(), e); } } }
From source file:com.netflix.paas.config.base.ConfigurationProxyUtils.java
static void assignFieldValues(final Object obj, Class<?> type, DynamicPropertyFactory propertyFactory, AbstractConfiguration configuration) throws Exception { // Iterate through all fields and set initial value as well as set up dynamic properties // where necessary for (final Field field : type.getFields()) { Configuration c = field.getAnnotation(Configuration.class); if (c == null) continue; String defaultValue = field.get(obj).toString(); String name = ConfigurationProxyUtils.getPropertyName(field, c); Supplier<?> supplier = ConfigurationProxyUtils.getStaticSupplier(field.getType(), name, defaultValue, configuration);/* w w w . j a va2s . com*/ field.set(obj, supplier.get()); if (field.getAnnotation(Dynamic.class) != null) { final PropertyWrapper<?> property; if (field.getType().isAssignableFrom(String.class)) { property = propertyFactory.getStringProperty(name, defaultValue); } else if (field.getType().isAssignableFrom(Integer.class)) { property = propertyFactory.getIntProperty(name, defaultValue == null ? 0 : Integer.parseInt(defaultValue)); } else if (field.getType().isAssignableFrom(Double.class)) { property = propertyFactory.getDoubleProperty(name, defaultValue == null ? 0.0 : Double.parseDouble(defaultValue)); } else if (field.getType().isAssignableFrom(Long.class)) { property = propertyFactory.getLongProperty(name, defaultValue == null ? 0L : Long.parseLong(defaultValue)); } else if (field.getType().isAssignableFrom(Boolean.class)) { property = propertyFactory.getBooleanProperty(name, defaultValue == null ? false : Boolean.parseBoolean(defaultValue)); } else { throw new RuntimeException("Unsupported type " + field.getType()); } property.addCallback(new Runnable() { @Override public void run() { try { field.set(obj, property.getValue()); } catch (Exception e) { e.printStackTrace(); } } }); } } }
From source file:com.github.rvesse.airline.Accessor.java
@SuppressWarnings("unchecked") private static Collection<Object> getOrCreateCollectionField(String name, Object object, Field field) { Collection<Object> collection; try {/*from w ww . j a v a 2s . c om*/ collection = (Collection<Object>) field.get(object); } catch (Exception e) { throw new ParseException(e, "Error getting collection field %s for argument %s", field.getName(), name); } if (collection == null) { collection = newCollection(field.getType()); try { field.set(object, collection); } catch (Exception e) { throw new ParseException(e, "Error setting collection field %s for argument %s", field.getName(), name); } } return collection; }
From source file:com.ms.commons.test.classloader.IntlTestURLClassPath.java
synchronized public static void initIntlTestURLClassLoader() { if (!isIntlTestURLClassPathInited) { try {// ww w.j a v a 2 s. c o m System.err.println(">>>>>> Begin 'IntlTestURLClassPath'. >>>>>>>>>>>>>>>>>>"); long BEGIN = System.currentTimeMillis(); System.err.println("Current classloader: " + IntlTestURLClassPath.class.getClassLoader()); { URLClassLoader loader = (URLClassLoader) Launcher.getLauncher().getClassLoader(); Field ucpField = URLClassLoader.class.getDeclaredField("ucp"); ucpField.setAccessible(true); IntlTestURLClassPath itucp = new IntlTestURLClassPath(getLauncherUrlClassPath(loader)); ucpField.set(loader, itucp); } // deal with "org.apache.maven.surefire.booter.IsolatedClassLoader" if (ISOLATED_CLASS_LOADER .equals(IntlTestURLClassPath.class.getClassLoader().getClass().getName())) { System.err.println( " >> Begin 'org.apache.maven.surefire.booter.IsolatedClassLoader'. >>>>>>>>>>>>>>>>>>"); URLClassLoader isoLoader = (URLClassLoader) IntlTestURLClassPath.class.getClassLoader(); Field isoUcpField = URLClassLoader.class.getDeclaredField("ucp"); isoUcpField.setAccessible(true); IntlTestURLClassPath isoItucp = new IntlTestURLClassPath(getLauncherUrlClassPath(isoLoader)); isoUcpField.set(isoLoader, isoItucp); System.err.println( " << Init 'org.apache.maven.surefire.booter.IsolatedClassLoader' successfuled. <<<<<<"); } System.err.println("Do 'IntlTestURLClassPath' cost:" + (System.currentTimeMillis() - BEGIN)); System.err.println("<<<<<< Init 'IntlTestURLClassPath' successfuled. <<<<<<"); isIntlTestURLClassPathInited = true; } catch (Exception e) { throw ExceptionUtil.wrapToRuntimeException(e); } } }
From source file:net.buffalo.protocal.util.ClassUtil.java
public static void setFieldValue(Object obj, String property, Object value) { Class type = obj.getClass();//from ww w . j a v a 2s .co m Field field = null; ClassFieldNamePair pair = new ClassFieldNamePair(type, property); if (fieldCache.get(pair) == null) { field = (Field) getFieldMap(type).get(property); if (field != null) { fieldCache.put(pair, field); } else { throw new AccessFieldException("Cannot find field [" + property + "] for " + type); } } else { field = (Field) fieldCache.get(pair); } try { try { field.set(obj, value); } catch (IllegalArgumentException ex) { field.set(obj, convertValue(value, field.getType())); } } catch (SecurityException e) { throw new net.buffalo.protocal.AccessFieldException(e); } catch (IllegalAccessException e) { throw new net.buffalo.protocal.AccessFieldException(e); } }
From source file:com.kcs.core.utilities.Utility.java
public static void nullToEmptyString(final Object obj) { ReflectionUtils.doWithFields(obj.getClass(), new ReflectionUtils.FieldCallback() { @Override/*from www. j a v a 2 s.c o m*/ public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException { field.setAccessible(true); if (Utility.isNull(field.get(obj))) { Class<?> clazz = field.getType(); if (clazz == String.class) { field.set(obj, StringUtil.BLANK); } } } }); }
From source file:com.liferay.cli.support.util.ReflectionUtils.java
/** * Set the field represented by the supplied {@link Field field object} on * the specified {@link Object target object} to the specified * <code>value</code>. In accordance with {@link Field#set(Object, Object)} * semantics, the new value is automatically unwrapped if the underlying * field has a primitive type./*w w w . ja va 2s .c o m*/ * <p> * Thrown exceptions are handled via a call to * {@link #handleReflectionException(Exception)}. * * @param field the field to set * @param target the target object on which to set the field * @param value the value to set; may be <code>null</code> */ public static void setField(final Field field, final Object target, final Object value) { try { field.set(target, value); } catch (final IllegalAccessException ex) { handleReflectionException(ex); throw new IllegalStateException( "Unexpected reflection exception - " + ex.getClass().getName() + ": " + ex.getMessage()); } }
From source file:com.lonepulse.zombielink.proxy.Zombie.java
/** * <p>Accepts an object and scans it for {@link Bite} annotations. If found, a <b>thread-safe proxy</b> * for the endpoint interface will be injected.</p> * /*from w ww.j a v a 2 s . c om*/ * <p>Injection targets will be searched up an inheritance hierarchy until a type is found which is * <b>not</b> in a package whose name starts with the given package prefixes.</p> * <br> * <b>Usage:</b> * <br><br> * <ul> * <li> * <h5>Property Injection</h5> * <pre> * <code><b>@Bite</b> * private GitHubEndpoint gitHubEndpoint; * { * Zombie.infect(Arrays.asList("com.example.service", "com.example.manager"), this); * } * </code> * </pre> * </li> * <li> * <h5>Setter Injection</h5> * <pre> * <code><b>@Bite</b> * private GitHubEndpoint gitHubEndpoint; * { * Zombie.infect(Arrays.asList("com.example.service", "com.example.manager"), this); * } * </code> * <code> * public void setGitHubEndpoint(GitHubEndpoint gitHubEndpoint) { * * this.gitHubEndpoint = gitHubEndpoint; * } * </code> * </pre> * </li> * </ul> * * @param packagePrefixes * the prefixes of packages to restrict hierarchical lookup of injection targets; if {@code null} * or {@code empty}, {@link #infect(Object, Object...)} will be used * <br><br> * @param victim * an object with endpoint references marked to be <i>bitten</i> and infected * <br><br> * @param moreVictims * more unsuspecting objects with endpoint references to be infected * <br><br> * @throws NullPointerException * if the object supplied for endpoint injection is {@code null} * <br><br> * @since 1.3.0 */ public static void infect(List<String> packagePrefixes, Object victim, Object... moreVictims) { assertNotNull(victim); List<Object> injectees = new ArrayList<Object>(); injectees.add(victim); if (moreVictims != null && moreVictims.length > 0) { injectees.addAll(Arrays.asList(moreVictims)); } Class<?> endpointInterface = null; for (Object injectee : injectees) { Class<?> type = injectee.getClass(); do { for (Field field : Fields.in(type).annotatedWith(Bite.class)) { try { endpointInterface = field.getType(); Object proxyInstance = EndpointProxyFactory.INSTANCE.create(endpointInterface); try { //1.Simple Field Injection field.set(injectee, proxyInstance); } catch (IllegalAccessException iae) { //2.Setter Injection String fieldName = field.getName(); String mutatorName = "set" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1); try { Method mutator = injectee.getClass().getDeclaredMethod(mutatorName, endpointInterface); mutator.invoke(injectee, proxyInstance); } catch (NoSuchMethodException nsme) { //3.Forced Field Injection field.setAccessible(true); field.set(injectee, proxyInstance); } } } catch (Exception e) { Logger.getLogger(Zombie.class.getName()).log(Level.SEVERE, new StringBuilder().append("Failed to inject the endpoint proxy instance of type ") .append(endpointInterface.getName()).append(" on property ") .append(field.getName()).append(" at ") .append(injectee.getClass().getName()).append(". ").toString(), e); } } type = type.getSuperclass(); } while (!hierarchyTerminal(type, packagePrefixes)); } }
From source file:com.lonepulse.robozombie.proxy.Zombie.java
/** * <p>Accepts an object and scans it for {@link Bite} annotations. If found, a <b>thread-safe proxy</b> * for the endpoint interface will be injected.</p> * /*from www .ja v a2 s . c om*/ * <p>Injection targets will be searched up an inheritance hierarchy until a type is found which is * <b>not</b> in a package whose name starts with the given package prefixes.</p> * <br> * <b>Usage:</b> * <br><br> * <ul> * <li> * <h5>Property Injection</h5> * <pre> * <code><b>@Bite</b> * private GitHubEndpoint gitHubEndpoint; * { * Zombie.infect(Arrays.asList("com.example.service", "com.example.manager"), this); * } * </code> * </pre> * </li> * <li> * <h5>Setter Injection</h5> * <pre> * <code><b>@Bite</b> * private GitHubEndpoint gitHubEndpoint; * { * Zombie.infect(Arrays.asList("com.example.service", "com.example.manager"), this); * } * </code> * <code> * public void setGitHubEndpoint(GitHubEndpoint gitHubEndpoint) { * * this.gitHubEndpoint = gitHubEndpoint; * } * </code> * </pre> * </li> * </ul> * * @param packagePrefixes * the prefixes of packages to restrict hierarchical lookup of injection targets; if {@code null} * or {@code empty}, {@link #infect(Object, Object...)} will be used * <br><br> * @param victim * an object with endpoint references marked to be <i>bitten</i> and infected * <br><br> * @param moreVictims * more unsuspecting objects with endpoint references to be infected * <br><br> * @throws NullPointerException * if the object supplied for endpoint injection is {@code null} * <br><br> * @since 1.3.0 */ public static void infect(List<String> packagePrefixes, Object victim, Object... moreVictims) { assertNotNull(victim); List<Object> injectees = new ArrayList<Object>(); injectees.add(victim); if (moreVictims != null && moreVictims.length > 0) { injectees.addAll(Arrays.asList(moreVictims)); } Class<?> endpointInterface = null; for (Object injectee : injectees) { Class<?> type = injectee.getClass(); do { for (Field field : Fields.in(type).annotatedWith(Bite.class)) { try { endpointInterface = field.getType(); Object proxyInstance = EndpointProxyFactory.INSTANCE.create(endpointInterface); try { //1.Simple Field Injection field.set(injectee, proxyInstance); } catch (IllegalAccessException iae) { //2.Setter Injection String fieldName = field.getName(); String mutatorName = "set" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1); try { Method mutator = injectee.getClass().getDeclaredMethod(mutatorName, endpointInterface); mutator.invoke(injectee, proxyInstance); } catch (NoSuchMethodException nsme) { //3.Forced Field Injection field.setAccessible(true); field.set(injectee, proxyInstance); } } } catch (Exception e) { Log.e(Zombie.class.getName(), new StringBuilder().append("Failed to inject the endpoint proxy instance of type ") .append(endpointInterface.getName()).append(" on property ") .append(field.getName()).append(" at ") .append(injectee.getClass().getName()).append(". ").toString(), e); } } type = type.getSuperclass(); } while (!hierarchyTerminal(type, packagePrefixes)); } }
From source file:com.conversantmedia.mapreduce.tool.DistributedResourceManager.java
public static void setFieldValue(Field field, Object bean, Object value) throws IllegalAccessException { // Set it on the field field.setAccessible(true);//from www. j a v a 2s. c o m // Perform type conversion if possible.. SimpleTypeConverter converter = new SimpleTypeConverter(); try { value = converter.convertIfNecessary(value, field.getType()); } catch (ConversionNotSupportedException e) { // If conversion isn't supported, ignore and try and set anyway. } field.set(bean, value); }