Example usage for java.lang.reflect Field getClass

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

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:gr.abiss.calipso.jpasearch.specifications.GenericSpecifications.java

protected static boolean isAcceptableSimpleSearchFieldClass(Field tmpField) {
    return tmpField.getClass().isEnum() || tmpField.getType().equals(String.class);
}

From source file:org.jtester.module.utils.InjectionModuleHelper.java

/**
 * Performs auto-injection on a field by type of the objectToInject into the
 * given target object or targetClass, depending on the value of isStatic.
 * The object is injected on one single field, if there is more than one
 * candidate field, a {@link JTesterException} is thrown. We try to inject
 * the object on the most specific field, this means that when there are
 * muliple fields of one of the super-types or implemented interfaces of the
 * field, the one that is lowest in the hierarchy is chosen (if possible,
 * otherwise, a {@link JTesterException} is thrown.
 * /*from ww w. j a v  a2  s  .  c o  m*/
 * @param objectToInject
 *            The object that is injected
 * @param objectToInjectType
 *            The type of the object that is injected
 * @param target
 *            The target object (only used when isStatic is false)
 * @param targetClass
 *            The target class (only used when isStatis is true)
 * @param isStatic
 *            Indicates wether injection should be performed on the target
 *            object or on the target class
 * @return The object that was replaced by the injection
 */
private static Object injectIntoFieldByType(Object objectToInject, Type objectToInjectType, Object target,
        Class<?> targetClass, boolean isStatic) {
    // Try to find a field with an exact matching type
    Field fieldToInjectTo = null;
    Set<Field> fieldsWithExactType = getFieldsOfType(targetClass, objectToInjectType, isStatic);
    if (fieldsWithExactType.size() > 1) {
        StringBuilder message = new StringBuilder("More than one " + (isStatic ? "static " : "")
                + "field with type " + objectToInjectType + " found in " + targetClass.getSimpleName() + ".");
        if (objectToInjectType instanceof Class<?>) {
            message.append(" If the target is a generic type, this can be caused by type erasure.");
        }
        message.append(" Specify the target field explicitly instead of injecting into by type.");
        throw new JTesterException(message.toString());

    } else if (fieldsWithExactType.size() == 1) {
        fieldToInjectTo = fieldsWithExactType.iterator().next();

    } else {
        // Try to find a supertype field:
        // If one field exist that has a type which is more specific than
        // all other fields of the given type,
        // this one is taken. Otherwise, an exception is thrown
        Set<Field> fieldsOfType = getFieldsAssignableFrom(targetClass, objectToInjectType, isStatic);
        if (fieldsOfType.size() == 0) {
            throw new JTesterException("No " + (isStatic ? "static " : "") + "field with (super)type "
                    + objectToInjectType + " found in " + targetClass.getSimpleName());
        }
        for (Field field : fieldsOfType) {
            boolean moreSpecific = true;
            for (Field compareToField : fieldsOfType) {
                if (field != compareToField) {
                    if (field.getClass().isAssignableFrom(compareToField.getClass())) {
                        moreSpecific = false;
                        break;
                    }
                }
            }
            if (moreSpecific) {
                fieldToInjectTo = field;
                break;
            }
        }
        if (fieldToInjectTo == null) {
            throw new JTesterException("Multiple candidate target " + (isStatic ? "static " : "")
                    + "fields found in " + targetClass.getSimpleName()
                    + ", with none of them more specific than all others.");
        }
    }

    // Field to inject into found, inject the object and return old value
    Object oldValue = null;
    try {
        oldValue = getFieldValue(target, fieldToInjectTo);

    } catch (Exception e) {
        logger.warn(
                "Unable to retrieve current value of field to inject into. Will not be able to restore value after injection.",
                e);
    }
    setFieldValue(target, fieldToInjectTo, objectToInject);
    return oldValue;
}

From source file:io.github.wysohn.triggerreactor.tools.ReflectionUtil.java

public static Map<String, Object> extractVariablesWithEnumAsString(Object e) {
    Map<String, Object> map = new HashMap<String, Object>();

    Class<?> clazz = e.getClass();
    for (Field field : getAllFields(new ArrayList<Field>(), clazz)) {
        field.setAccessible(true);/*ww  w . ja va2 s .c  o  m*/
        try {
            if (field.getClass().isEnum()) {
                Enum<?> enumVal = (Enum<?>) field.get(e);
                map.put(field.getName(), enumVal.name());
            } else {
                map.put(field.getName(), field.get(e));
            }
        } catch (IllegalArgumentException | IllegalAccessException e1) {
            e1.printStackTrace();
        }
    }

    return map;
}

From source file:org.unitils.inject.util.InjectionUtils.java

/**
 * Performs auto-injection on a field by type of the objectToInject into the given target object or targetClass,
 * depending on the value of isStatic. The object is injected on one single field, if there is more than one
 * candidate field, a {@link UnitilsException} is thrown. We try to inject the object on the most specific field,
 * this means that when there are muliple fields of one of the super-types or implemented interfaces of the field,
 * the one that is lowest in the hierarchy is chosen (if possible, otherwise, a {@link UnitilsException} is thrown.
 *
 * @param objectToInject     The object that is injected
 * @param objectToInjectType The type of the object that is injected
 * @param target             The target object (only used when isStatic is false)
 * @param targetClass        The target class (only used when isStatis is true)
 * @param isStatic           Indicates wether injection should be performed on the target object or on the target class
 * @return The object that was replaced by the injection
 *//*from w w  w.  ja v  a2s .co m*/
private static Object injectIntoFieldByType(Object objectToInject, Type objectToInjectType, Object target,
        Class<?> targetClass, boolean isStatic) {
    // Try to find a field with an exact matching type
    Field fieldToInjectTo = null;
    Set<Field> fieldsWithExactType = getFieldsOfType(targetClass, objectToInjectType, isStatic);
    if (fieldsWithExactType.size() > 1) {
        StringBuilder message = new StringBuilder("More than one " + (isStatic ? "static " : "")
                + "field with type " + objectToInjectType + " found in " + targetClass.getSimpleName() + ".");
        if (objectToInjectType instanceof Class<?>) {
            message.append(" If the target is a generic type, this can be caused by type erasure.");
        }
        message.append(" Specify the target field explicitly instead of injecting into by type.");
        throw new UnitilsException(message.toString());

    } else if (fieldsWithExactType.size() == 1) {
        fieldToInjectTo = fieldsWithExactType.iterator().next();

    } else {
        // Try to find a supertype field:
        // If one field exist that has a type which is more specific than all other fields of the given type,
        // this one is taken. Otherwise, an exception is thrown
        Set<Field> fieldsOfType = getFieldsAssignableFrom(targetClass, objectToInjectType, isStatic);
        if (fieldsOfType.size() == 0) {
            throw new UnitilsException("No " + (isStatic ? "static " : "") + "field with (super)type "
                    + objectToInjectType + " found in " + targetClass.getSimpleName());
        }
        for (Field field : fieldsOfType) {
            boolean moreSpecific = true;
            for (Field compareToField : fieldsOfType) {
                if (field != compareToField) {
                    if (field.getClass().isAssignableFrom(compareToField.getClass())) {
                        moreSpecific = false;
                        break;
                    }
                }
            }
            if (moreSpecific) {
                fieldToInjectTo = field;
                break;
            }
        }
        if (fieldToInjectTo == null) {
            throw new UnitilsException("Multiple candidate target " + (isStatic ? "static " : "")
                    + "fields found in " + targetClass.getSimpleName()
                    + ", with none of them more specific than all others.");
        }
    }

    // Field to inject into found, inject the object and return old value
    Object oldValue = null;
    try {
        oldValue = getFieldValue(target, fieldToInjectTo);

    } catch (Exception e) {
        logger.warn(
                "Unable to retrieve current value of field to inject into. Will not be able to restore value after injection.",
                e);
    }
    setFieldValue(target, fieldToInjectTo, objectToInject);
    return oldValue;
}

From source file:org.openmainframe.ade.impl.PropertyAnnotation.java

static public String getHelp(Object obj) {
    final StringBuilder helpString = new StringBuilder();
    final Class<?> annotatedClass = obj.getClass();
    for (Field field : annotatedClass.getDeclaredFields()) {
        final Property annos = field.getAnnotation(Property.class);
        if (annos != null) {
            helpString.append("name=" + annos.key() + ", " + "type =" + field.getClass().getSimpleName()
                    + (annos.required() ? " required " : " ") + ": " + annos.help() + "\n");
        }//ww w  .j  ava2 s .  c  o  m
    }
    return helpString.toString();
}

From source file:ca.uhn.fhir.context.ModelScanner.java

static Class<?> determineElementType(Field next) {
    Class<?> nextElementType = next.getType();
    if (List.class.equals(nextElementType)) {
        nextElementType = ReflectionUtil.getGenericCollectionTypeOfField(next);
    } else if (Collection.class.isAssignableFrom(nextElementType)) {
        throw new ConfigurationException(
                "Field '" + next.getName() + "' in type '" + next.getClass().getCanonicalName()
                        + "' is a Collection - Only java.util.List curently supported");
    }//w  w  w.j av a 2 s  .  c  om
    return nextElementType;
}

From source file:org.opendaylight.sxp.route.core.RoutingServiceFactoryTest.java

private void changeOsIsLinuxField(final boolean mockedOsName)
        throws NoSuchFieldException, IllegalAccessException {
    final Field osNameField = SystemUtils.class.getDeclaredField("IS_OS_LINUX");
    osNameField.setAccessible(true);//from  w  w w  .  ja va  2 s.  c  om
    Field modifiers = osNameField.getClass().getDeclaredField("modifiers");
    modifiers.setAccessible(true);
    modifiers.setInt(osNameField, osNameField.getModifiers() & ~Modifier.FINAL);
    osNameField.set(null, mockedOsName);
}

From source file:org.jgentleframework.core.factory.InOutExecutor.java

/**
 * Executes method outject.//  w w w . j  a v a  2  s.  c om
 * 
 * @param getters
 *            the getters
 * @param provider
 *            the provider
 * @param target
 *            the target
 * @param definition
 *            the definition
 * @throws IllegalArgumentException
 *             the illegal argument exception
 * @throws IllegalAccessException
 *             the illegal access exception
 * @throws InvocationTargetException
 *             the invocation target exception
 */
public static void executesMethodOutjecting(Method[] getters, Provider provider, Object target,
        Definition definition)
        throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {

    if (getters != null) {
        for (int i = 0; i < getters.length; i++) {
            Definition defMethod = definition.getMemberDefinition(getters[i]);
            if (defMethod == null)
                continue;
            else {
                Class<?> returnType = getters[i].getReturnType();
                Object[] args = Utils.getInjectedParametersOf(getters[i], defMethod, provider);
                Object outjectObj = null;
                getters[i].setAccessible(true);
                outjectObj = args.length == 0 ? getters[i].invoke(target) : getters[i].invoke(target, args);
                Outject outject = defMethod.getAnnotation(Outject.class);
                Field field = null;
                try {
                    field = Utils.getFieldOfDefaultSetGetter(getters[i], (Class<?>) definition.getKey());
                } catch (InvalidOperationException e) {
                    throw new InOutDependencyException(e.getMessage());
                } catch (NoSuchFieldException e) {
                }
                /*
                 * Executes builder
                 */
                if (ReflectUtils.isCast(Builder.class, target)) {
                    Builder builder = (Builder) target;
                    if (builder.getOutjectValue(field) != null)
                        outjectObj = builder.getOutjectValue(field);
                }
                // executes outjection
                Class<?> type = field != null ? field.getClass() : returnType;
                InOutExecutor.setOutjectedDependency(outject, outjectObj, provider, type);
            }
        }
    }
}

From source file:edu.brown.statistics.AbstractStatistics.java

protected String debug(Database catalog_db, Enum<?> elements[]) {
    Map<String, Object> m = new ListOrderedMap<String, Object>();
    try {//from  w ww  .ja v  a  2  s.  c  o  m
        Class<?> statsClass = this.getClass();
        for (Enum<?> element : elements) {
            Field field = statsClass.getDeclaredField(element.toString().toLowerCase());
            Object value = field.get(this);

            if (field.getClass().isAssignableFrom(SortedMap.class)) {
                SortedMap<?, ?> orig_value = (SortedMap<?, ?>) value;
                Map<String, Object> inner_m = new ListOrderedMap<String, Object>();
                for (Object inner_key : orig_value.keySet()) {
                    Object inner_val = orig_value.get(inner_key);
                    if (inner_val instanceof AbstractStatistics<?>) {
                        inner_val = ((AbstractStatistics<?>) inner_val).debug(catalog_db);
                    }
                    inner_m.put(inner_key.toString(), inner_val);
                } // FOR
                value = StringUtil.formatMaps(inner_m);
            }
            m.put(element.toString(), value);
        } // FOR
    } catch (Exception ex) {
        ex.printStackTrace();
        System.exit(1);
    }
    return (String.format("%s\n%s", this.getCatalogItem(catalog_db),
            StringUtil.prefix(StringUtil.formatMaps(m), DEBUG_SPACER)));
}

From source file:com.neusoft.mid.clwapi.tools.JacksonUtils.java

/**
 * @param obj/*from  w  w w  .  j  a  v a2s. c  om*/
 * @param f
 * @throws IllegalAccessException
 * @throws JacksonEncoderException
 */
private static Object jsonCoder(Object obj, Field f) throws IllegalAccessException, JacksonEncoderException {
    Object o = FieldUtils.readField(f, obj);
    if (o instanceof String) {
        FieldUtils.writeField(f, obj, jsonCoder((String) o, true));
    } else if (o instanceof Collection<?>) {
        logger.debug("Field [" + f.getName() + "] is " + o.getClass());
        Collection<?> c = (Collection<?>) o;
        Iterator<?> it = c.iterator();
        while (it.hasNext()) {
            jsonEncoder(it.next());
        }
    } else if (o instanceof Map<?, ?>) {
        logger.debug("Field [" + f.getName() + "] is " + o.getClass());
        Set<?> entries = ((Map<?, ?>) o).entrySet();
        Iterator<?> it = entries.iterator();
        while (it.hasNext()) {
            Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) it.next();
            logger.debug("Key is [" + entry.getKey() + "]");
            entry.setValue(jsonEncoder(entry.getValue()));
        }
    } else if (o instanceof Integer || o instanceof Byte || o instanceof Boolean || o instanceof Long
            || o instanceof Double || o instanceof Character || o instanceof Short || o instanceof Float
            || o instanceof Number) {
        return obj;
    } else {
        throw new JacksonEncoderException("??" + f.getClass());
    }
    return obj;
}