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:net.ceos.project.poi.annotated.core.CellHandler.java

/**
 * Read a date time value from the Cell.
 * /*from  w  w w  .  jav  a2s  . c o m*/
 * @param object
 *            the object
 * @param field
 *            the {@link Field} to set
 * @param cell
 *            the {@link Cell} to read
 * @param xlsAnnotation
 *            the {@link XlsElement} element
 * @throws ConverterException
 *             the conversion exception type
 */
protected static void localDateTimeReader(final Object object, final Field field, final Cell cell,
        final XlsElement xlsAnnotation) throws ConverterException {
    if (StringUtils.isNotBlank(readCell(cell))) {
        try {
            if (StringUtils.isBlank(xlsAnnotation.transformMask())) {
                field.set(object,
                        cell.getDateCellValue().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
            } else {
                String date = cell.getStringCellValue();

                String tM = xlsAnnotation.transformMask();
                String fM = xlsAnnotation.formatMask();
                String decorator = StringUtils.isEmpty(tM)
                        ? (StringUtils.isEmpty(fM) ? CellStyleHandler.MASK_DECORATOR_DATE : fM)
                        : tM;

                SimpleDateFormat dt = new SimpleDateFormat(decorator);
                Date dateConverted = dt.parse(date);
                field.set(object, dateConverted.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
            }
        } catch (ParseException | IllegalArgumentException | IllegalAccessException e) {
            /*
             * if date decorator do not match with a valid mask launch
             * exception
             */
            throw new ConverterException(ExceptionMessage.CONVERTER_LOCALDATETIME.getMessage(), e);
        }
    }
}

From source file:com.addthis.hydra.task.stream.TestStreamSourceMeshy.java

@Test
public void testStreamSourcesSort() {
    final StreamSourceMeshy source = new StreamSourceMeshy();
    final int numElements = 100000;

    FileReference[] fileRefs = new FileReference[numElements];
    List<MeshyStreamFile> streamFiles = new ArrayList<>(numElements);
    DateTime date = DateTime.now();//from  ww w .ja v  a  2s  .c o m

    try {
        for (int i = 0; i < numElements; i++) {
            fileRefs[i] = new FileReference("", 0, i);
            Field f = fileRefs[i].getClass().getDeclaredField("hostUUID");
            f.setAccessible(true);
            String uuid = RandomStringUtils.randomAlphabetic(20);
            f.set(fileRefs[i], uuid);
            streamFiles.add(new MeshyStreamFile(source, date, fileRefs[i]));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        fail();
    }

    Collections.shuffle(streamFiles);

    Collections.sort(streamFiles, new Comparator<MeshyStreamFile>() {
        @Override
        public int compare(MeshyStreamFile streamFile1, MeshyStreamFile streamFile2) {
            return source.compareStreamFiles(streamFile1, streamFile2);
        }
    });

}

From source file:com.github.glue.mvc.RequestHandler.java

public void handle() throws Exception {
    Class actionClass = definition.getTarget().getDeclaringClass();
    Object action = container.getInstance(actionClass);

    VarMapper[] paramMappers = definition.getParamMappers();
    Object[] parameters = new Object[paramMappers.length];
    for (int i = 0; i < paramMappers.length; i++) {
        parameters[i] = paramMappers[i].getVar(this);
    }/* w w w  . jav  a  2s . com*/

    Map<Field, VarMapper> fieldMappers = definition.getFieldMappers();
    for (Map.Entry<Field, VarMapper> entry : fieldMappers.entrySet()) {
        Field field = entry.getKey();
        VarMapper varMapper = entry.getValue();
        Object value = varMapper.getVar(this);
        field.set(action, value);
    }

    Object executeResult = definition.getTarget().invoke(action, parameters);

    //renderView
    if (executeResult instanceof Reply) {
        Reply reply = (Reply) executeResult;
        reply.populate(container, request, response);
    } else {
        log.warn("Return Object should be Reply instance.");
    }
}

From source file:com.marvelution.bamboo.plugins.sonar.tasks.processors.SonarBuildPasswordProcessor.java

/**
 * {@inheritDoc}/*from ww  w  .  ja  v  a2 s.  com*/
 */
@Override
public void intercept(LogEntry logEntry) {
    if (logEntry instanceof SimpleLogEntry) {
        String filtered = filterPasswords(logEntry.getUnstyledLog());
        if (!filtered.equals(logEntry.getUnstyledLog())) {
            // The log entry line was changed update the LogEntry...
            try {
                Field logField = getField(logEntry);
                if (logField != null) {
                    logField.setAccessible(true);
                    logField.set(logEntry, filtered);
                }
            } catch (Exception e) {
                LOGGER.debug("Failed to filter the Sonar password from LogEntry: " + e.getMessage(), e);
            }
        }
    }
}

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

/**
 * Read a date time value from the Cell.
 * /*from   w w w .  java 2 s. c om*/
 * @param object
 *            the object
 * @param field
 *            the {@link Field} to set
 * @param cell
 *            the {@link Cell} to read
 * @param xlsAnnotation
 *            the {@link XlsElement} element
 * @throws ConverterException
 *             the conversion exception type
 */
protected static void localDateReader(final Object object, final Field field, final Cell cell,
        final XlsElement xlsAnnotation) throws ConverterException {

    if (StringUtils.isNotBlank(readCell(cell))) {
        try {
            if (StringUtils.isBlank(xlsAnnotation.transformMask())) {
                field.set(object,
                        cell.getDateCellValue().toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
            } else {
                String date = cell.getStringCellValue();

                String tM = xlsAnnotation.transformMask();
                String fM = xlsAnnotation.formatMask();
                String decorator = StringUtils.isEmpty(tM)
                        ? (StringUtils.isEmpty(fM) ? CellStyleHandler.MASK_DECORATOR_DATE : fM)
                        : tM;

                SimpleDateFormat dt = new SimpleDateFormat(decorator);

                Date dateConverted = dt.parse(date);
                field.set(object, dateConverted.toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
            }
        } catch (ParseException | IllegalArgumentException | IllegalAccessException e) {
            /*
             * if date decorator do not match with a valid mask launch
             * exception
             */
            throw new ConverterException(ExceptionMessage.CONVERTER_LOCALDATE.getMessage(), e);
        }
    }
}

From source file:org.example.mybatis.spring.MultipleSqlSessionTemplate.java

private void resetSqlSessionProxy() {

    // Create new proxy.
    SqlSession sqlSessionProxy = (SqlSession) Proxy.newProxyInstance(SqlSessionFactory.class.getClassLoader(),
            new Class[] { SqlSession.class }, new MultipleSqlSessionInterceptor());

    // Overwrite to current proxy.
    try {//from w w  w . j av a  2 s  .c o m

        Field field = this.getClass().getSuperclass().getDeclaredField("sqlSessionProxy"); //$NON-NLS-1$
        field.setAccessible(true);
        field.set(this, sqlSessionProxy);
    } catch (Throwable e) {

        throw new RuntimeException(e);
    }
}

From source file:com.streamsets.datacollector.main.TestLogConfigurator.java

@After
public void cleanUp() throws Exception {
    System.getProperties().remove("log4j.configuration");
    System.getProperties().remove("log4j.defaultInitOverride");
    for (Thread thread : Thread.getAllStackTraces().keySet()) {
        if (thread instanceof FileWatchdog) {
            Field interrupted = ((Class) thread.getClass().getGenericSuperclass())
                    .getDeclaredField("interrupted");
            interrupted.setAccessible(true);
            interrupted.set(thread, true);
            thread.interrupt();/*from  w  w w  . java2 s . c o  m*/
        }
    }
}

From source file:org.constretto.spring.ConfigurationAnnotationConfigurer.java

private void injectEnvironment(final Object bean) {
    try {//from   ww w  . j  a  v  a  2  s  .c o  m
        Field[] fields = bean.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(Environment.class)) {
                field.setAccessible(true);
                field.set(bean, assemblyContextResolver.getAssemblyContext());
            }
        }
    } catch (IllegalAccessException e) {
        throw new BeanInstantiationException(bean.getClass(), "Could not inject Environment on spring bean");
    }
}

From source file:org.apache.sling.discovery.base.connectors.ping.TopologyRequestValidatorTest.java

private void setPrivate(Object o, String field, Object value)
        throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
    Field f = o.getClass().getDeclaredField(field);
    if (!f.isAccessible()) {
        f.setAccessible(true);/*from  ww  w.j a v  a2s  .  co m*/
    }
    f.set(o, value);
}

From source file:grails.plugin.miniprofiler.sitemesh.grails20.ProfilingGrailsPageFilter.java

@Override
public void init(FilterConfig fc) {
    super.init(fc);
    profilerProvider = WebApplicationContextUtils.getRequiredWebApplicationContext(fc.getServletContext())
            .getBean("profilerProvider", ProfilerProvider.class);

    Field field = null;
    try {// w  ww  . ja v a2s. c o m
        field = GrailsPageFilter.class.getDeclaredField("decoratorMapper");
        field.setAccessible(true);
        DecoratorMapper decoratorMapper = (DecoratorMapper) field.get(this);
        field.set(this, new ProfilingDecoratorMapper(decoratorMapper, profilerProvider));
    } catch (NoSuchFieldException e) {
        // different grails version which doesn't have that field?
    } catch (IllegalAccessException e) {
        // just won't work, we're in a security manager
    }
}