Example usage for org.springframework.util ReflectionUtils findField

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

Introduction

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

Prototype

@Nullable
public static Field findField(Class<?> clazz, @Nullable String name, @Nullable Class<?> type) 

Source Link

Document

Attempt to find a Field field on the supplied Class with the supplied name and/or Class type .

Usage

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);/*from  w w  w  .  j a va 2  s  . c  o m*/
    assertNotNull(bundleCreator.getRootPath());
    assertNotNull(bundleCreator.getBundleContentPattern());
    assertNotNull(bundleCreator.getManifestLocation());
}

From source file:io.pivotal.poc.gateway.filters.pre.FileClaimCheckFilter.java

public FileClaimCheckFilter(FileClaimCheckStore store) {
    super(2);//w  w  w .  j av  a  2s.  c  om
    Assert.notNull(store, "FileClaimCheckStore must not be null");
    this.store = store;
    this.requestField = ReflectionUtils.findField(HttpServletRequestWrapper.class, "req",
            HttpServletRequest.class);
    this.servletRequestField = ReflectionUtils.findField(ServletRequestWrapper.class, "request",
            ServletRequest.class);
    this.contentDataField = ReflectionUtils.findField(HttpServletRequestWrapper.class, "contentData",
            byte[].class);
    Assert.notNull(this.requestField, "HttpServletRequestWrapper.req field not found");
    Assert.notNull(this.servletRequestField, "ServletRequestWrapper.request field not found");
    Assert.notNull(this.contentDataField, "HttpServletRequestWrapper.contentData field not found");
    this.requestField.setAccessible(true);
    this.servletRequestField.setAccessible(true);
    this.contentDataField.setAccessible(true);
}

From source file:org.eclipse.gemini.blueprint.test.internal.holder.HolderLoader.java

public HolderLoader() {
    // try to load the holder using the app ClassLoader
    ClassLoader appCL = Bundle.class.getClassLoader();
    Class<?> clazz;//  w  w w  .jav a2s . co  m
    try {
        clazz = appCL.loadClass(HOLDER_CLASS_NAME);
    } catch (Exception ex) {
        // if it's not found, then the class path is incorrectly constructed
        throw (RuntimeException) new IllegalStateException(
                "spring-osgi-test.jar is not available on the boot class path; are you deploying the test framework"
                        + "as a bundle by any chance? ").initCause(ex);
    }
    // get the static instance
    Field field = ReflectionUtils.findField(clazz, INSTANCE_FIELD, clazz);
    Object instance;
    try {
        instance = field.get(null);
    } catch (Exception ex) {
        throw (RuntimeException) new IllegalStateException("Cannot read property " + INSTANCE_FIELD)
                .initCause(ex);
    }
    // once the class is loaded return it wrapped through it's OSGi instance
    holder = new ReflectionOsgiHolder(instance);
}

From source file:py.una.pol.karaku.replication.client.ReplicationResponseHandler.java

/**
 * @param response//  w w  w  .ja  va2  s  .co m
 * @return
 */
@SuppressWarnings("rawtypes")
private Collection getItems(Object response) {

    Object respuesta = notNull(response, "Cant get changes from null response");
    Class<?> clazz = notNull(respuesta.getClass());
    Field f = KarakuReflectionUtils.findField(clazz, CHANGE_FIELDS);

    if (f == null) {
        f = ReflectionUtils.findField(response.getClass(), null, List.class);
    }

    notNull(f,
            "Cant get the id field, " + "use the @ReplicationData annotation or create "
                    + "a field with name %s, please see %s",
            Arrays.toString(CHANGE_FIELDS), response.getClass().getName());
    f.setAccessible(true);
    Collection c = (Collection) ReflectionUtils.getField(f, response);

    if (c == null) {
        return Collections.EMPTY_LIST;
    }
    return c;
}

From source file:com.brienwheeler.lib.jmx.logging.Log4jMBeanExporter.java

@SuppressWarnings("unchecked")
private synchronized void shutdown() {
    shutdown = true;//from w  w w .j  a v  a 2s .  c om
    killDelayedThread();

    MBeanServer server = JmxUtils.locateMBeanServer();
    HierarchyDynamicMBean hdm = hierarchyDynamicMBean.get();
    for (ObjectName registeredName : registeredNames) {
        try {
            server.unregisterMBean(registeredName);

            // The AbstractDynamicMBean base class of the HierarchyDynamicMBean tracks these names too
            // and will later try to unregister them and throw warning log messages unless we violate its
            // privacy and clean out its internal bookkeeping
            Field fld = ReflectionUtils.findField(hdm.getClass(), "mbeanList", Vector.class);
            fld.setAccessible(true);
            Vector<ObjectName> mbeanList = (Vector<ObjectName>) ReflectionUtils.getField(fld, hdm);
            mbeanList.remove(registeredName);
        } catch (Exception e) {
            log.error("Error unregistering " + registeredName.getCanonicalName(), e);
        }
    }
    registeredNames.clear();

    if (registeredHierarchy) {
        try {
            ObjectName mbo = new ObjectName(LOG4J_HIERARCHY_DEFAULT);
            server.unregisterMBean(mbo);
        } catch (Exception e) {
            log.error("Error unregistering Log4j MBean Hierarchy", e);
        }
        registeredHierarchy = false;
    }
}

From source file:org.eclipse.virgo.ide.ui.editors.SpringBundleSourcePage.java

@Override
public IDocumentRange findRange() {
    try {//from   w w  w  .  j  a  v  a2s  .c o  m
        java.lang.reflect.Field field = ReflectionUtils.findField(this.getClass(), "fSelection", Object.class);
        field.setAccessible(true);
        Object selection = field.get(this);

        if (selection instanceof ImportLibraryObject) {
            return getSpecificRange(((ImportLibraryObject) selection).getModel(),
                    IHeaderConstants.IMPORT_LIBRARY, ((ImportLibraryObject) selection).getId());
        } else if (selection instanceof ImportBundleObject) {
            return getSpecificRange(((ImportBundleObject) selection).getModel(), IHeaderConstants.IMPORT_BUNDLE,
                    ((ImportBundleObject) selection).getId());
        } else if (selection instanceof ImportPackageObject) {
            ImportPackageObject impObj = (ImportPackageObject) selection;
            String key = impObj.getHeader().getKey();
            if (key != null && key.equalsIgnoreCase(IHeaderConstants.IMPORT_TEMPLATE)) {
                return getSpecificRange(((ImportPackageObject) selection).getModel(),
                        IHeaderConstants.IMPORT_TEMPLATE, ((ImportPackageObject) selection).getValue());
            } else if (key != null && key.equalsIgnoreCase(IHeaderConstants.EXCLUDED_IMPORTS)) {
                return getSpecificRange(((ImportPackageObject) selection).getModel(),
                        IHeaderConstants.EXCLUDED_IMPORTS, ((ImportPackageObject) selection).getValue());
            } else if (key != null && key.equalsIgnoreCase(IHeaderConstants.UNVERSIONED_IMPORTS)) {
                return getSpecificRange(((ImportPackageObject) selection).getModel(),
                        IHeaderConstants.UNVERSIONED_IMPORTS, ((ImportPackageObject) selection).getValue());
            }
        } else if (selection instanceof ExportPackageObject) {
            ExportPackageObject expObj = (ExportPackageObject) selection;
            String key = expObj.getHeader().getKey();
            if (key != null && key.equalsIgnoreCase(IHeaderConstants.EXPORT_TEMPLATE)) {
                return getSpecificRange(((ExportPackageObject) selection).getModel(),
                        IHeaderConstants.EXPORT_TEMPLATE, ((ExportPackageObject) selection).getValue());
            } else if (key != null && key.equalsIgnoreCase(IHeaderConstants.EXCLUDED_EXPORTS)) {
                return getSpecificRange(((ExportPackageObject) selection).getModel(),
                        IHeaderConstants.EXCLUDED_EXPORTS, ((ExportPackageObject) selection).getValue());
            }
        } else {
            return super.findRange();
        }
    } catch (Exception e) {
    }
    return super.findRange();
}

From source file:org.apache.dubbo.config.spring.beans.factory.annotation.CompatibleReferenceAnnotationBeanPostProcessor.java

private <T> T getFieldValue(Object object, String fieldName, Class<T> fieldType) {

    Field field = ReflectionUtils.findField(object.getClass(), fieldName, fieldType);

    ReflectionUtils.makeAccessible(field);

    return (T) ReflectionUtils.getField(field, object);

}

From source file:org.springframework.data.gemfire.RegionFactoryBean.java

@SuppressWarnings("unchecked")
private AttributesFactory<K, V> findAttrFactory(RegionFactory<K, V> regionFactory) {
    Field attrField = ReflectionUtils.findField(RegionFactory.class, "attrsFactory", AttributesFactory.class);
    ReflectionUtils.makeAccessible(attrField);
    return (AttributesFactory<K, V>) ReflectionUtils.getField(attrField, regionFactory);
}

From source file:org.springframework.test.util.ReflectionTestUtils.java

/**
 * Set the {@linkplain Field field} with the given {@code name}/{@code type}
 * on the provided {@code targetObject}/{@code targetClass} to the supplied
 * {@code value}.//from  w  ww.  j  ava 2 s.com
 * <p>If the supplied {@code targetObject} is a <em>proxy</em>, it will
 * be {@linkplain AopTestUtils#getUltimateTargetObject unwrapped} allowing
 * the field to be set on the ultimate target of the proxy.
 * <p>This method traverses the class hierarchy in search of the desired
 * field. In addition, an attempt will be made to make non-{@code public}
 * fields <em>accessible</em>, thus allowing one to set {@code protected},
 * {@code private}, and <em>package-private</em> fields.
 * @param targetObject the target object on which to set the field; may be
 * {@code null} if the field is static
 * @param targetClass the target class on which to set the field; may
 * be {@code null} if the field is an instance field
 * @param name the name of the field to set; may be {@code null} if
 * {@code type} is specified
 * @param value the value to set
 * @param type the type of the field to set; may be {@code null} if
 * {@code name} is specified
 * @since 4.2
 * @see ReflectionUtils#findField(Class, String, Class)
 * @see ReflectionUtils#makeAccessible(Field)
 * @see ReflectionUtils#setField(Field, Object, Object)
 * @see AopTestUtils#getUltimateTargetObject(Object)
 */
public static void setField(@Nullable Object targetObject, @Nullable Class<?> targetClass,
        @Nullable String name, @Nullable Object value, @Nullable Class<?> type) {

    Assert.isTrue(targetObject != null || targetClass != null,
            "Either targetObject or targetClass for the field must be specified");

    if (targetObject != null && springAopPresent) {
        targetObject = AopTestUtils.getUltimateTargetObject(targetObject);
    }
    if (targetClass == null) {
        targetClass = targetObject.getClass();
    }

    Field field = ReflectionUtils.findField(targetClass, name, type);
    if (field == null) {
        throw new IllegalArgumentException(
                String.format("Could not find field '%s' of type [%s] on %s or target class [%s]", name, type,
                        safeToString(targetObject), targetClass));
    }

    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Setting field '%s' of type [%s] on %s or target class [%s] to value [%s]",
                name, type, safeToString(targetObject), targetClass, value));
    }
    ReflectionUtils.makeAccessible(field);
    ReflectionUtils.setField(field, targetObject, value);
}