Example usage for org.springframework.util ReflectionUtils makeAccessible

List of usage examples for org.springframework.util ReflectionUtils makeAccessible

Introduction

In this page you can find the example usage for org.springframework.util ReflectionUtils makeAccessible.

Prototype

@SuppressWarnings("deprecation") 
public static void makeAccessible(Field field) 

Source Link

Document

Make the given field accessible, explicitly setting it accessible if necessary.

Usage

From source file:com.javaetmoi.core.spring.vfs.Vfs2ResourceHandlerRegistration.java

@Override
protected ResourceHttpRequestHandler getRequestHandler() {
    Field locationsField = ReflectionUtils.findField(ResourceHandlerRegistration.class, "locations");
    ReflectionUtils.makeAccessible(locationsField);
    @SuppressWarnings("unchecked")
    List<Resource> locations = (List<Resource>) ReflectionUtils.getField(locationsField, this);

    Field cachePeriodField = ReflectionUtils.findField(ResourceHandlerRegistration.class, "cachePeriod");
    ReflectionUtils.makeAccessible(cachePeriodField);
    Integer cachePeriod = (Integer) ReflectionUtils.getField(cachePeriodField, this);

    // Initial code is replace by a new Vfs2ResourceHttpRequestHandler()
    Assert.isTrue(!CollectionUtils.isEmpty(locations),
            "At least one location is required for resource handling.");
    ResourceHttpRequestHandler requestHandler = new Vfs2ResourceHttpRequestHandler();
    requestHandler.setLocations(locations);
    if (cachePeriod != null) {
        requestHandler.setCacheSeconds(cachePeriod);
    }//from  w ww.j  a  v a  2s  . c o  m
    return requestHandler;
}

From source file:com.ciphertool.sentencebuilder.etl.parsers.FrequencyFileParserTest.java

@Test
public void testSetFilename() {
    String fileNameToSet = "arbitraryFileName";
    FrequencyFileParser frequencyFileParser = new FrequencyFileParser();
    frequencyFileParser.setFileName(fileNameToSet);

    Field fileNameField = ReflectionUtils.findField(FrequencyFileParser.class, "fileName");
    ReflectionUtils.makeAccessible(fileNameField);
    String fileNameFromObject = (String) ReflectionUtils.getField(fileNameField, frequencyFileParser);

    assertSame(fileNameToSet, fileNameFromObject);
}

From source file:com.github.javarch.support.log.LoggingAnnotationBeanPostProcessor.java

private void injectLogger(Object bean, Field field) {
    ReflectionUtils.makeAccessible(field);
    ReflectionUtils.setField(field, bean, LoggerFactory.getLogger(field.getDeclaringClass()));
}

From source file:com.dianping.avatar.cache.util.CacheAnnotationUtils.java

/**
 * Retrieve the cache key values from entity instance
 *//*from w w w.j  a v  a 2  s. co  m*/
public static Object[] getCacheKeyValues(Object entity) {
    if (entity == null) {
        throw new IllegalArgumentException("Entity is null.");
    }

    Class<?> cz = entity.getClass();

    Cache cache = cz.getAnnotation(Cache.class);

    if (cache == null) {
        throw new SystemException("The entity must be annotated by Cache.");
    }

    Field[] fields = ClassUtils.getDeclaredFields(cz);

    final List<OrderedField> cacheFields = new ArrayList<OrderedField>();

    // Extract annotated fields
    for (int i = 0; i < fields.length; i++) {
        Field f = fields[i];
        CacheParam fCache = f.getAnnotation(CacheParam.class);
        if (fCache != null) {
            cacheFields.add(new OrderedField(f, i, fCache.order()));
        }
    }

    // Extract declared fields
    for (int i = 0; i < cache.fields().length; i++) {
        String fieldName = cache.fields()[i];
        if (fieldName.isEmpty()) {
            continue;
        }
        Field f = ReflectionUtils.findField(cz, fieldName);
        if (f == null) {
            throw new IllegalArgumentException(
                    "Invalid cahce parameter " + fieldName + ", the filed is not exists.");
        }

        cacheFields.add(new OrderedField(f, i, -Integer.MAX_VALUE + i));
    }

    Collections.sort(cacheFields);

    Object[] values = new Object[cacheFields.size()];

    for (int i = 0; i < cacheFields.size(); i++) {
        OrderedField oField = cacheFields.get(i);

        ReflectionUtils.makeAccessible((Field) oField.field);

        values[i] = ReflectionUtils.getField((Field) oField.field, entity);
    }

    return values;
}

From source file:com.blstream.hooks.springframework.mongodb.event.ListCascadingMongoEventListener.java

public void onBeforeConvert(final Object source) {
    ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() {

        @Override/*  w  w  w  . ja va  2s. c  om*/
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            ReflectionUtils.makeAccessible(field);

            if (field.isAnnotationPresent(DBRef.class) && field.isAnnotationPresent(DBRefListCascade.class)) {
                final Object fieldValue = field.get(source);

                if (fieldValue instanceof Collection<?>) {
                    Collection<?> collectionField = (Collection<?>) fieldValue;

                    for (Object collectionFieldElement : collectionField) {
                        DbRefFieldCallback callback = new DbRefFieldCallback();

                        ReflectionUtils.doWithFields(collectionFieldElement.getClass(), callback);

                        if (!callback.isIdFound()) {
                            throw new MappingException(
                                    "Cannot perform cascade save on child object without id set");
                        }

                        mongoOperations.save(fieldValue);
                    }

                } else {
                    throw new MappingException(
                            "Cannot perform cascade save using DBRefListCascade annotation on not collection bean.");
                }
            }
        }
    });
}

From source file:com.ciphertool.sentencebuilder.etl.parsers.PartOfSpeechFileParserTest.java

@Test
public void testSetFilename() {
    String fileNameToSet = "arbitraryFileName";
    PartOfSpeechFileParser partOfSpeechFileParser = new PartOfSpeechFileParser();
    partOfSpeechFileParser.setFileName(fileNameToSet);

    Field fileNameField = ReflectionUtils.findField(PartOfSpeechFileParser.class, "fileName");
    ReflectionUtils.makeAccessible(fileNameField);
    String fileNameFromObject = (String) ReflectionUtils.getField(fileNameField, partOfSpeechFileParser);

    assertSame(fileNameToSet, fileNameFromObject);
}

From source file:com.orange.clara.cloud.boot.ssl.SslDefaultTrustStoreAppenderListenerTest.java

@Before
public void setup() throws IllegalArgumentException, IllegalAccessException {
    sslTrustStoreGeneratorListener = new SslTrustStoreGeneratorListener();
    Field envField = ReflectionUtils.findField(SslTrustStoreGeneratorListener.class, "propertyResolver");
    ReflectionUtils.makeAccessible(envField);
    ReflectionUtils.setField(envField, sslTrustStoreGeneratorListener, propertyResolver);
    Field sslCertTrusterField = ReflectionUtils.findField(SslTrustStoreGeneratorListener.class,
            "trustStoreAppender");
    ReflectionUtils.makeAccessible(sslCertTrusterField);
    ReflectionUtils.setField(sslCertTrusterField, sslTrustStoreGeneratorListener, trustStoreAppender);
}

From source file:my.adam.smo.common.LoggerInjector.java

@Override
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
    ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            ReflectionUtils.makeAccessible(field);
            if (field.getAnnotation(InjectLogger.class) != null) {
                Logger logger = LoggerFactory.getLogger(bean.getClass());
                field.set(bean, logger);
            }//w  w  w  .j av  a  2s. com
        }
    });

    return bean;
}

From source file:org.eclipse.gemini.blueprint.test.ConfigurableBundleCreatorTestsTest.java

public void testDefaultJarSettings() throws Exception {

    Properties defaultSettings = bundleCreator.getSettings();
    Field field = ReflectionUtils.findField(AbstractConfigurableBundleCreatorTests.class, "jarSettings",
            Properties.class);
    ReflectionUtils.makeAccessible(field);
    ReflectionUtils.setField(field, null, defaultSettings);
    assertNotNull(defaultSettings);// ww w  .  j a  v  a 2  s.co  m
    assertNotNull(bundleCreator.getRootPath());
    assertNotNull(bundleCreator.getBundleContentPattern());
    assertNotNull(bundleCreator.getManifestLocation());
}

From source file:cn.org.once.cstack.cli.processor.LoggerPostProcessor.java

public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
    ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {

        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {

            if (field.getAnnotation(InjectLogger.class) != null && field.getType().equals(Logger.class)) {
                ReflectionUtils.makeAccessible(field);
                Logger logger = Logger.getLogger(bean.getClass().getName());

                field.set(bean, logger);

                StreamHandler fileHandler;
                try {

                    FileOutputStream fileOutputStream = new FileOutputStream(new File("errors.log"), true);
                    fileHandler = new StreamHandler(fileOutputStream, new SimpleFormatter());
                    fileHandler.setLevel(Level.SEVERE);
                    logger.addHandler(fileHandler);

                } catch (SecurityException | IOException e) {
                    throw new IllegalArgumentException(e);
                }/* w w  w . j  a va  2s. c  o m*/

            }
        }
    });

    return bean;
}