Example usage for org.apache.commons.lang3.reflect FieldUtils getField

List of usage examples for org.apache.commons.lang3.reflect FieldUtils getField

Introduction

In this page you can find the example usage for org.apache.commons.lang3.reflect FieldUtils getField.

Prototype

public static Field getField(final Class<?> cls, final String fieldName, final boolean forceAccess) 

Source Link

Document

Gets an accessible Field by name, breaking scope if requested.

Usage

From source file:com.robertsmieja.test.utils.junit.GettersAndSettersUtils.java

/**
 * Run the tests only on one specific field for the passed in objects
 *
 * @param value          An instance of the object under test
 * @param differentValue An instance of the object under test that contains different values in it's fields
 * @param fieldName      The name of hte field to test
 * @param <T>            The class under test
 *
 * @throws InvocationTargetException/*from w  w  w  . ja  v a2s. c  o m*/
 * @throws IllegalAccessException
 */
public static <T> void runGettersAndSettersTestOnField(T value, T differentValue, String fieldName)
        throws InvocationTargetException, IllegalAccessException {
    Class<?> aClass = value.getClass();
    Field field = FieldUtils.getField(aClass, fieldName, true);
    if (field == null) {
        Assertions.fail("Field <" + fieldName + "> not found on <" + aClass + ">");
    }
    runGettersAndSettersTestOnField(value, differentValue, field);
}

From source file:com.opensymphony.xwork2.util.ProxyUtil.java

/**
 * Check whether the given class has a given member.
 * @param clazz the class to check//from www  .  ja v a2  s. c  om
 * @param member the member to check
 */
private static boolean hasMember(Class<?> clazz, Member member) {
    if (member instanceof Method) {
        return null != MethodUtils.getMatchingMethod(clazz, member.getName(),
                ((Method) member).getParameterTypes());
    }
    if (member instanceof Field) {
        return null != FieldUtils.getField(clazz, member.getName(), true);
    }
    if (member instanceof Constructor) {
        return null != ConstructorUtils.getMatchingAccessibleConstructor(clazz,
                ((Constructor) member).getParameterTypes());
    }

    return false;
}

From source file:com.joyent.manta.client.MantaObjectOutputStream.java

/**
 * Uses reflection to look into the specified {@link OutputStream} instance to
 * see if there is a boolean field set called "closed", if it is set and accessible
 * via reflection, we return its value. Otherwise, we return null.
 *
 * @param stream instance to reflect on for closed property
 * @return reference to closed property or null if unavailable
 *///from ww w.ja va 2  s  . co  m
protected static Boolean isInnerStreamClosed(final OutputStream stream) {
    OutputStream inner = findMostInnerOutputStream(stream);

    // If the inner most stream is a closed instance, then we can assume
    // the stream is close.
    if (inner.getClass().equals(ClosedOutputStream.class)) {
        return true;
    }

    try {
        Field f = FieldUtils.getField(inner.getClass(), "closed", true);

        if (f == null) {
            throw new IllegalArgumentException("FieldUtils.getField(inner.getClass()) " + "returned null");
        }

        Object result = f.get(inner);
        return (boolean) result;
    } catch (IllegalArgumentException | IllegalAccessException | ClassCastException e) {
        String msg = String.format("Error finding [closed] field on class: %s", inner.getClass());
        LOGGER.warn(msg, e);
        /* If we don't have an inner field called closed, it is inaccessible or
         * the field isn't a boolean, return null because we are now dealing with
         * undefined behavior. */
        return null;
    }
}

From source file:com.joyent.manta.client.multipart.AbstractMultipartManager.java

/**
 * <p>Uses reflection to read a private field from a {@link MantaClient}
 * instance.</p>//from   w ww . j  a v  a  2  s  .  c  om
 *
 * <p>We use reflection to read private fields from {@link MantaClient} as
 * part of a compromise between package level separation and private/default
 * scoping. Essentially, it makes sense to put multipart related classes
 * in their own package because the package in which {@link MantaClient} is
 * contained is already crowded. However, by making that decision there is
 * no scoping mechanism available in Java to allow us to share
 * methods/fields between packages without giving other packages access.
 * Thus, we scope the methods/fields that shouldn't be available to a user
 * of the SDK as private/protected/default and use reflection
 * <em>sparingly</em> to access the values from another package. Particular
 * care has been paid to making this reflection-based reads outside of
 * performance sensitive code paths.</p>
 *
 * @param fieldName field name to read
 * @param mantaClient Manta client instance to read fields from
 * @param returnType type of field
 * @param <T> field type
 * @return value of the field
 */
protected static <T> T readFieldFromMantaClient(final String fieldName, final MantaClient mantaClient,
        final Class<T> returnType) {
    final Field field = FieldUtils.getField(MantaClient.class, fieldName, true);

    try {
        Object object = FieldUtils.readField(field, mantaClient, true);
        return returnType.cast(object);
    } catch (IllegalAccessException e) {
        throw new MantaMultipartException("Unable to access httpHelper " + "field on MantaClient");
    }
}

From source file:com.validation.manager.core.history.Versionable.java

public static synchronized boolean auditable(Versionable v) {
    History current;//w w  w.  ja  v a 2s . c  om
    boolean result = false;
    if (v.getHistoryList() != null && !v.getHistoryList().isEmpty()) {
        current = v.getHistoryList().get(v.getHistoryList().size() - 1);
        for (HistoryField hf : current.getHistoryFieldList()) {
            try {
                //Compare audit field vs. the record in history.
                Object o = FieldUtils.readField(FieldUtils.getField(v.getClass(), hf.getFieldName(), true), v);
                if ((o == null && !hf.getFieldValue().equals("null"))
                        || (!(o instanceof byte[]) && o != null && !o.toString().equals(hf.getFieldValue()))
                        || ((o instanceof byte[]) && !new String((byte[]) o, StandardCharsets.UTF_8)
                                .equals(hf.getFieldValue()))) {
                    result = true;
                    break;
                }
            } catch (SecurityException | IllegalArgumentException | IllegalAccessException ex) {
                LOG.log(Level.SEVERE, null, ex);
            }
        }
        //As last check the version fields for changes (i.e. baselineing, etc.)
        if (!result) {
            result = current.getMajorVersion() < v.getMajorVersion()
                    || current.getMidVersion() < v.getMidVersion()
                    || current.getMinorVersion() < v.getMinorVersion();
        }
        return result;
    }
    //No history so it is auditable if it has marked fields for audit.
    return !FieldUtils.getFieldsListWithAnnotation(v.getClass(), Auditable.class).isEmpty();
}

From source file:com.joyent.manta.client.MantaObjectOutputStream.java

/**
 * Finds the most inner stream if the embedded stream is stored on the passed
 * stream as a field named <code>out</code>. This hold true for all classes
 * that extend {@link java.io.FilterOutputStream}.
 *
 * @param stream stream to search for inner stream
 * @return reference to inner stream class
 *//* w w w.j a  v a2s .  c o  m*/
protected static OutputStream findMostInnerOutputStream(final OutputStream stream) {
    Field f = FieldUtils.getField(stream.getClass(), "out", true);

    if (f == null) {
        return stream;
    } else {
        try {
            Object result = f.get(stream);

            if (result instanceof OutputStream) {
                return findMostInnerOutputStream((OutputStream) result);
            } else {
                return stream;
            }
        } catch (IllegalAccessException e) {
            // If we can't access the field, then we just return back the original stream
            return stream;
        }
    }
}

From source file:com.garethahealy.camel.dynamic.loadbalancer.statistics.mbeans.MBeanRouteStatisticsCollector.java

/**
 * Get the uri from the processor (NOTE: Current impl uses reflection, so could fail easily)
 *
 * @param current//from  w  w  w . j ava 2s  .  c  o  m
 * @return
 */
private String getUriFromProcessor(Processor current) {
    String uri = "";

    //NOTE: What if camel uses different 'Channels', this wont work.
    // How can i get the URI from the processor in a nice way?

    if (current instanceof DefaultChannel) {
        DefaultChannel currentChannel = (DefaultChannel) current;

        Object outputValue = null;
        try {
            //NOTE: Shouldnt really be using reflection...but dont know what class i can use
            Field outputField = FieldUtils.getField(DefaultChannel.class, "childDefinition", true);
            outputValue = FieldUtils.readField(outputField, currentChannel, true);
        } catch (IllegalAccessException ex) {
            LOG.error("Cannot access 'childDefinition' on {} because: {}", current,
                    ExceptionUtils.getStackTrace(ex));
        }

        //NOTE: What if the definition isnt a To, its another type...
        if (outputValue != null && outputValue instanceof ToDefinition) {
            ToDefinition to = (ToDefinition) outputValue;

            uri = normalizeUri(to.getUri());
        }
    }

    if (uri.isEmpty()) {
        throw new IllegalStateException("Could not get URI from processor '" + current + "'");
    }

    return uri;
}

From source file:com.ethlo.geodata.restdocs.AbstractJacksonFieldSnippet.java

protected void handleSchema(final Class<?> type, final ObjectNode root, final ObjectNode definitions,
        FieldDescriptor desc, final Iterator<String> path) {
    ObjectNode lastNode = (ObjectNode) root.get("properties");
    Class<?> lastField = type;
    while (path.hasNext() && lastNode != null && lastField != null) {
        final String p = StringUtils.replace(path.next(), "[]", "");
        final Field f = FieldUtils.getField(lastField, p, true);

        final Class<?> field = f != null ? (Collection.class.isAssignableFrom(f.getType())
                ? (Class<?>) ((ParameterizedType) f.getGenericType()).getActualTypeArguments()[0]
                : f.getType()) : null;//w  w w  .j a  v  a2 s.  co  m
        final JsonNode currentNode = lastNode.get(p);
        if (currentNode instanceof ObjectNode && field != null) {
            if (!path.hasNext()) {
                // Leaf of path definition, set description
                final String description = desc.getDescription().toString();
                ((ObjectNode) currentNode).put("description", description);
            }

            final String typeDef = currentNode.path("type").asText();
            if (!StringUtils.isNotEmpty(typeDef)) {
                handleRef(field, root, definitions, (ObjectNode) currentNode, desc, path);
            }
        }

        lastNode = currentNode instanceof ObjectNode ? (ObjectNode) currentNode : null;
        lastField = field;
    }
}

From source file:com.thinkbiganalytics.metadata.modeshape.datasource.JcrDatasourceProvider.java

@Override
public String getNodeType(Class<? extends JcrEntity> jcrEntityType) {
    try {//from   w w w. ja  v  a2  s  .c  o m
        Field folderField = FieldUtils.getField(jcrEntityType, "NODE_TYPE", true);
        String jcrType = (String) folderField.get(null);
        return jcrType;
    } catch (IllegalArgumentException | IllegalAccessException e) {
        // Shouldn't really happen.
        throw new MetadataException("Unable to determine JCR node the for entity class: " + jcrEntityType, e);
    }
}

From source file:com.thinkbiganalytics.policy.BasePolicyAnnotationTransformer.java

/**
 * Trasform a user interface object back to the domain policy class
 *
 * @param rule the ui object//from  www .  j a va 2 s  .c  o m
 * @return the domain policy transformed
 */
@Override
public P fromUiModel(U rule) throws PolicyTransformException {
    try {
        P domainPolicy = createClass(rule);

        if (hasConstructor(domainPolicy.getClass())) {

            for (FieldRuleProperty property : rule.getProperties()) {
                String field = property.getObjectProperty();
                String value = property.getStringValue();
                Field f = FieldUtils.getField(domainPolicy.getClass(), field, true);
                Object objectValue = convertStringToObject(value, f.getType());
                f.set(domainPolicy, objectValue);
            }
        }
        afterFromUiModel(domainPolicy, rule);
        return domainPolicy;
    } catch (Exception e) {
        throw new PolicyTransformException(e);
    }
}