Example usage for java.lang.reflect Field getType

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

Introduction

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

Prototype

public Class<?> getType() 

Source Link

Document

Returns a Class object that identifies the declared type for the field represented by this Field object.

Usage

From source file:Main.java

/**
 * Get a list of the name of variables of the class received
 * @param klass Class to get the variable names
 * @return List<String>[] of length 3 with variable names: [0]: primitives, [1]: arrays, [2]: objects
 *//*  w  w w .j av a2  s.  c o m*/
public static List<String>[] getVariableNames(Class klass) {

    //array to return
    List<String>[] varNames = new List[3];
    for (int i = 0; i < 3; i++) {
        varNames[i] = new ArrayList<>();
    }

    //add all valid fields
    do {
        Field[] fields = klass.getDeclaredFields();
        for (Field field : fields) {
            if (!Modifier.isTransient(field.getModifiers())) {

                //get the type
                Class type = field.getType();

                if (type.isPrimitive() || (type == Integer.class) || (type == Float.class)
                        || (type == Double.class) || (type == Boolean.class) || (type == String.class)) {
                    varNames[0].add(field.getName());
                } else if (type.isArray()) {
                    varNames[1].add(field.getName());
                } else {
                    varNames[2].add(field.getName());
                }
            }
        }

        klass = klass.getSuperclass();
    } while (klass != null);

    //return array
    return varNames;

}

From source file:ch.ifocusit.plantuml.utils.ClassUtils.java

public static Set<Class> getConcernedTypes(Field field) {
    Set<Class> classes = new HashSet<>();
    classes.add(field.getType());
    classes.addAll(getGenericTypes(field));
    return classes;
}

From source file:natalia.dymnikova.cluster.scheduler.impl.Codec.java

private static Object doSanitize(final Object f) {
    final Class<?> aClass = f.getClass();
    if (!isStatic(aClass.getModifiers())) {
        final Class<?> enclosingClass = aClass.getEnclosingClass();
        if (enclosingClass != null) {
            for (final Field field : aClass.getDeclaredFields()) {
                if (enclosingClass.equals(field.getType())) {
                    field.setAccessible(true);
                    try {
                        field.set(f, null);
                    } catch (final IllegalAccessException e) {
                        throw unchecked(e);
                    }//from  w  ww.  j  av a2s .  com
                }
            }
        }
    }
    return f;
}

From source file:fr.juanwolf.mysqlbinlogreplicator.component.DomainClassAnalyzer.java

static boolean isInteger(Field field) {
    return field.getType() == Integer.class || field.getType() == int.class;
}

From source file:Main.java

/**
 * This method will iterate over all the fields on an object searching for declared fields defined as
 * Collection, List, Set, Map type.  If those fields are null they will be set to empty unmodifiable
 * instances.  If those fields are not null then it will force them to be unmodifiable.
 *
 * This method does not handle nested types.
 *
 * @param o the object to modify.  a null object will do nothing.
 *///ww  w  .  j a  va2s .  com
public static void makeUnmodifiableAndNullSafe(Object o) throws IllegalAccessException {
    if (o == null) {
        return;
    }

    Class<?> targetClass = o.getClass();
    for (Field f : targetClass.getDeclaredFields()) {
        f.setAccessible(true);
        try {
            if (f.getType().isAssignableFrom(List.class)) {
                f.set(o, unmodifiableListNullSafe((List<?>) f.get(o)));
            } else if (f.getType().isAssignableFrom(Set.class)) {
                f.set(o, unmodifiableSetNullSafe((Set<?>) f.get(o)));
            } else if (f.getType().isAssignableFrom(Collection.class)) {
                f.set(o, unmodifiableCollectionNullSafe((Collection<?>) f.get(o)));
            } else if (f.getType().isAssignableFrom(Map.class)) {
                f.set(o, unmodifiableMapNullSafe((Map<?, ?>) f.get(o)));
            }
        } finally {
            f.setAccessible(false);
        }
    }
}

From source file:com.fengduo.bee.commons.util.ObjectUtils.java

/**
 * string?trim?/*from  www .j  a  v a 2  s.c o m*/
 * 
 * @param object
 * @throws Exception
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
private static void trimStringField(Object object, Class<?> clazz) throws Exception {
    if (object instanceof Map<?, ?>) {
        Map<Object, Object> target = new HashMap<Object, Object>();
        for (Entry<?, ?> entry : ((Map<?, ?>) object).entrySet()) {
            Object key = entry.getKey();
            Object value = entry.getValue();

            if (key instanceof String) {
                key = StringUtils.trim((String) key);
            } else {
                trim(key);
            }

            if (value instanceof String) {
                value = StringUtils.trim((String) value);
                value = StringUtils.replace((String) value, "\"", StringUtils.EMPTY);
            } else {
                trim(value);
            }
            target.put(key, value);
        }
        ((Map<?, ?>) object).clear();
        ((Map) object).putAll((Map) target);
        return;
    }
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        if (field.getType() == String.class) {
            boolean isFoolback = false;
            if (field.isAccessible() == false) {
                isFoolback = true;
                field.setAccessible(true);
            }
            String value = (String) field.get(object);
            if (StringUtils.isNotEmpty(value)) {
                value = value.trim();
                field.set(object, value);
            }
            if (isFoolback) {
                field.setAccessible(false);
            }
        }
    }
}

From source file:com.ejisto.modules.web.util.FieldSerializationUtil.java

private static MockedField translateField(Field field, Object container, String className, String contextPath) {
    Class<?> fieldType = field.getType();
    MockedField out = buildMockedField(className, field.getName(), contextPath, fieldType.getName());
    Object value = safeGet(field, container);
    if (value == null || isBlackListed(fieldType)) {
        out.setFieldValue(null);//from   w  ww .  j  a v  a2  s.c o  m
        return out;
    }
    int hashCode = System.identityHashCode(value);
    String existingClassMapping = CACHED_IDS.putIfAbsent(hashCode, out.getFieldType());
    if (StringUtils.isNotBlank(existingClassMapping)) {
        out.setLink(String.valueOf(hashCode));
        return out;
    } else if (field.isEnumConstant() || fieldType.isPrimitive()) {
        out.setFieldValue(String.valueOf(value));
    } else {
        out.setExpression(translateValue(value));
    }
    out.setRecordedObjectHashCode(hashCode);
    return out;
}

From source file:de.axelfaust.alfresco.nashorn.repo.web.scripts.RepositoryScriptLocation.java

protected static String tryAndGetField(final ScriptContent content, final String fieldName) {
    String result;//from   w ww . jav a2 s .com

    try {
        final Field field = content.getClass().getDeclaredField(fieldName);
        if (field.getType().isAssignableFrom(String.class)) {
            field.setAccessible(true);
            result = (String) field.get(content);
        } else {
            result = null;
        }
    } catch (final IllegalAccessException | NoSuchFieldException e) {
        result = null;
    }
    return result;
}

From source file:jfix.util.Reflections.java

/**
 * Returns true if given class can be assigned to given field (which might
 * be a simple field or array)./*from ww w.j a  v  a2 s .c om*/
 */
public static boolean isAssignable(Class<?> clazz, Field field) {
    return clazz.isAssignableFrom(field.getType())
            || (field.getType().isArray() && clazz.isAssignableFrom(field.getType().getComponentType()));
}

From source file:com.braffdev.server.core.container.injection.DependencyInjector.java

/**
 * Injects the given dependency to the given field of the given object.
 *
 * @param field the field to inject.// ww w . j a v a2  s  . c  om
 * @param target the object.
 * @param dependencyName the name of the dependency.
 * @param dependency the dependency to inject.
 */
private static void injectFieldDependency(Field field, Object target, String dependencyName,
        Object dependency) {
    Class<?> fieldClass = field.getType();
    if (!dependency.getClass().isAssignableFrom(fieldClass)) {
        LOGGER.error("Dependency \"" + dependencyName + "\"  (class " + dependency.getClass().getName()
                + ") cannot be injected. This class is not assignable from the target field");
        return;
    }

    try {
        field.setAccessible(true);
        field.set(target, dependency);

        LOGGER.debug("Injected dependency \"" + dependencyName + "\" of class \"" + target.getClass() + "\"");
    } catch (Throwable t) {
        LOGGER.error("Cannot inject dependency \"" + dependencyName + "\"", t);
    }
}