Example usage for java.lang Class getDeclaredFields

List of usage examples for java.lang Class getDeclaredFields

Introduction

In this page you can find the example usage for java.lang Class getDeclaredFields.

Prototype

@CallerSensitive
public Field[] getDeclaredFields() throws SecurityException 

Source Link

Document

Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object.

Usage

From source file:Mopex.java

/**
 * Returns an array of the instance variablies of the the specified class.
 * An instance variable is defined to be a non-static field that is declared
 * by the class or inherited.//from   ww w.  j  a v  a2s. c  o  m
 * 
 * @return java.lang.Field[]
 * @param cls
 *            java.lang.Class
 */
//start extract getInstanceVariables
public static Field[] getInstanceVariables(Class cls) {
    List accum = new LinkedList();
    while (cls != null) {
        Field[] fields = cls.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            if (!Modifier.isStatic(fields[i].getModifiers())) {
                accum.add(fields[i]);
            }
        }
        cls = cls.getSuperclass();
    }
    Field[] retvalue = new Field[accum.size()];
    return (Field[]) accum.toArray(retvalue);
}

From source file:com.qingstor.sdk.utils.QSJSONUtil.java

private static void setParameterToMap(Method m, Object source, Field f, Object data) {
    if (data != null) {
        try {//from   w w w.  j  a  v a  2s.  c  o  m
            if (data instanceof JSONArray || data instanceof JSONObject) {
                Class fClass = f.getType();
                if (fClass.equals(List.class)) {
                    List invokeData = new ArrayList();
                    ParameterizedType stringListType = (ParameterizedType) f.getGenericType();
                    Class<?> cls = (Class<?>) stringListType.getActualTypeArguments()[0];

                    if (cls.equals(String.class) || cls.equals(Integer.class) || cls.equals(Double.class)
                            || cls.equals(Long.class) || cls.equals(Float.class)) {
                        if (data instanceof JSONArray) {
                            JSONArray jsonData = (JSONArray) data;
                            for (int i = 0; i < jsonData.length(); i++) {

                                Object o = toObject(jsonData, i);
                                invokeData.add(o);
                            }
                        }
                    } else {
                        if (data instanceof JSONArray) {
                            JSONArray jsonData = (JSONArray) data;
                            for (int i = 0; i < jsonData.length(); i++) {
                                Object fObject = cls.newInstance();
                                JSONObject o = toJSONObject(jsonData, i);
                                Class tmpClass = fObject.getClass();
                                while (tmpClass != Object.class) {
                                    Field[] fields = tmpClass.getDeclaredFields();
                                    initParameter(o, fields, tmpClass, fObject);
                                    tmpClass = tmpClass.getSuperclass();
                                }
                                invokeData.add(fObject);
                            }
                        }
                    }

                    m.invoke(source, invokeData);

                } else if (fClass.equals(Map.class)) {
                    Map invokeData = new HashMap();
                    if (data instanceof JSONObject) {
                        JSONObject jsonData = (JSONObject) data;
                        for (int i = 0; i < jsonData.length(); i++) {
                            String key = toJSONObject(jsonData, i) + "";
                            Object value = toJSONObject(jsonData, key);
                            invokeData.put(key, value);
                        }
                    }
                    m.invoke(source, invokeData);
                } else {

                    Object invokeData = f.getType().newInstance();
                    Class tmpClass = invokeData.getClass();
                    while (tmpClass != Object.class) {
                        Field[] fields = tmpClass.getDeclaredFields();
                        initParameter((JSONObject) data, fields, tmpClass, invokeData);
                        tmpClass = tmpClass.getSuperclass();
                    }
                    m.invoke(source, invokeData);
                }

            } else {
                if (f.getType().equals(data.getClass())) {
                    m.invoke(source, data);
                } else {
                    m.invoke(source, getParseValue(f.getType(), data));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:org.mybatisorm.annotation.handler.TableHandler.java

public static List<Field> getFields(Class<?> clazz) {
    List<Field> fields = new ArrayList<Field>();
    Class<?> superClass = clazz.getSuperclass();
    if (TableHandler.hasAnnotation(superClass)) {
        fields.addAll(getFields(clazz.getSuperclass()));
    }//w  w  w  . j  a  v  a  2 s  .co  m
    fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
    return fields;
}

From source file:com.bosscs.spark.commons.utils.Utils.java

/**
 * Get all fields rec.//from  w ww  .j av a2  s  .  co  m
 *
 * @param clazz  the clazz
 * @param fields the fields
 * @return the field [ ]
 */
private static Field[] getAllFieldsRec(Class clazz, List<Field> fields) {
    Class superClazz = clazz.getSuperclass();
    if (superClazz != null) {
        getAllFieldsRec(superClazz, fields);
    }

    fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
    return fields.toArray(new Field[fields.size()]);
}

From source file:com.github.gekoh.yagen.ddl.TableConfig.java

private static <T extends Annotation> Set<AccessibleObject> getAnnotatedFieldOrMethod(
        Set<AccessibleObject> fieldsOrMethods, Class<T> annotationClass, Class entityClass,
        boolean withInheritance) {
    for (Field field : entityClass.getDeclaredFields()) {
        if (field.isAnnotationPresent(annotationClass)) {
            fieldsOrMethods.add(field);//  www.  j  av  a  2s . c o m
        }
    }
    for (Method method : entityClass.getDeclaredMethods()) {
        if (method.isAnnotationPresent(annotationClass)) {
            fieldsOrMethods.add(method);
        }
    }
    if (entityClass.getSuperclass() != null && withInheritance) {
        return getAnnotatedFieldOrMethod(fieldsOrMethods, annotationClass, entityClass.getSuperclass(),
                withInheritance);
    }
    return fieldsOrMethods;
}

From source file:com.liferay.cli.support.util.ReflectionUtils.java

/**
 * Attempt to find a {@link Field field} on the supplied {@link Class} with
 * the supplied <code>name</code> and/or {@link Class type}. Searches all
 * superclasses up to {@link Object}.//www .  j a  va  2s.  c  om
 * 
 * @param clazz the class to introspect
 * @param name the name of the field (may be <code>null</code> if type is
 *            specified)
 * @param type the type of the field (may be <code>null</code> if name is
 *            specified)
 * @return the corresponding Field object, or <code>null</code> if not found
 */
public static Field findField(final Class<?> clazz, final String name, final Class<?> type) {
    Validate.notNull(clazz, "Class must not be null");
    Validate.isTrue(name != null || type != null, "Either name or type of the field must be specified");
    Class<?> searchType = clazz;
    while (!Object.class.equals(searchType) && searchType != null) {
        final Field[] fields = searchType.getDeclaredFields();
        for (final Field field : fields) {
            if ((name == null || name.equals(field.getName()))
                    && (type == null || type.equals(field.getType()))) {
                return field;
            }
        }
        searchType = searchType.getSuperclass();
    }
    return null;
}

From source file:br.com.lucasisrael.regra.reflections.TratamentoReflections.java

/**
 * Invoke the given callback on all fields in the target class, going up the
 * class hierarchy to get all declared fields.
 * @param clazz the target class to analyze
 * @param fc the callback to invoke for each field
 * @param ff the filter that determines the fields to apply the callback to
 *//*from  w  w  w.  ja va 2  s  .c om*/
public static void doWithFields(Class<?> clazz, FieldCallback fc, FieldFilter ff)
        throws IllegalArgumentException {

    // Keep backing up the inheritance hierarchy.
    Class<?> targetClass = clazz;
    do {
        Field[] fields = targetClass.getDeclaredFields();
        for (Field field : fields) {
            // Skip static and final fields.
            if (ff != null && !ff.matches(field)) {
                continue;
            }
            try {
                fc.doWith(field);
            } catch (IllegalAccessException ex) {
                throw new IllegalStateException(
                        "Shouldn't be illegal to access field '" + field.getName() + "': " + ex);
            }
        }
        targetClass = targetClass.getSuperclass();
    } while (targetClass != null && targetClass != Object.class);
}

From source file:com.jk.util.JKObjectUtil.java

/**
 * Gets the instance variables.//from  ww w. j av a  2  s . c o  m
 *
 * @param <T>
 *            the generic type
 * @param clas
 *            the clas
 * @return the instance variables
 */
public static <T> String getInstanceVariables(Class<T> clas) {
    StringBuffer fieldsString = new StringBuffer();
    Field[] fields = clas.getDeclaredFields();
    int i = 0;
    for (Field field : fields) {
        if (i++ > 0) {
            fieldsString.append(JK.CSV_SEPARATOR);
        }
        fieldsString.append(field.getName());
    }
    return fieldsString.toString();
}

From source file:com.yukthi.utils.beans.PropertyMapper.java

/**
 * Checks in the cache if the specified bean type property details is already loaded. If loaded returns the same. If not, builds the property map
 * caches it and returns it.//from  w  w w.j  a v  a  2  s.  co m
 * @param beanType Bean types for which property map needs to be fetched
 * @return Property details of specified bean type
 */
public static synchronized BeanInfo getBeanInfo(Class<?> beanType) {
    BeanInfo beanInfo = typeToProp.get(beanType);

    //if type is already loaded return the same
    if (beanInfo != null) {
        return beanInfo;
    }

    beanInfo = new BeanInfo(beanType);
    Field fields[] = null;
    NestedProperty nestedProp = null;
    IgnorePropertyDestination ignorePropertyDestination = null;

    while (!beanType.getName().startsWith("java")) {
        fields = beanType.getDeclaredFields();

        //loop through property descriptors and add to bean property map
        for (Field field : fields) {
            try {
                nestedProp = NestedProperty.getNestedProperty(beanType, field.getName());
            } catch (Exception ex) {
                logger.info("Ignoring {}.{} property, as property fetch resulted in error - {}",
                        beanType.getName(), field.getName(), ex);
                continue;
            }

            ignorePropertyDestination = field.getAnnotation(IgnorePropertyDestination.class);

            beanInfo.addProperty(new PropertyInfo(nestedProp, ignorePropertyDestination != null));

            getMappingsFromField(beanInfo, field);
        }

        beanType = beanType.getSuperclass();
    }

    //cache and return property map
    typeToProp.put(beanType, beanInfo);
    return beanInfo;
}

From source file:acmi.l2.clientmod.xdat.Controller.java

private static TreeItem<Object> createTreeItem(IOEntity o) {
    TreeItem<Object> item = new TreeItem<>(o);

    List<Field> fields = new ArrayList<>();
    Class<?> clazz = o.getClass();
    while (clazz != Object.class) {
        Arrays.stream(clazz.getDeclaredFields()).filter(field -> !field.isSynthetic())
                .filter(field -> List.class.isAssignableFrom(field.getType())
                        || IOEntity.class.isAssignableFrom(field.getType()))
                .forEach(fields::add);//from  w  w  w .  j  a va2s  .  co  m
        clazz = clazz.getSuperclass();
    }
    fields.forEach(field -> {
        field.setAccessible(true);

        Optional<Object> obj = Optional.empty();
        try {
            obj = Optional.ofNullable(field.get(o));
        } catch (IllegalAccessException e) {
            log.log(Level.WARNING, String.format("%s.%s is not accessible", o.getClass(), field.getName()), e);
            Dialogs.show(Alert.AlertType.ERROR, "ReflectiveOperationException", null,
                    String.format("%s.%s is not accessible", o.getClass(), field.getName()));
        }

        obj.ifPresent(val -> {
            if (List.class.isAssignableFrom(field.getType())) {
                if (!field.isAnnotationPresent(Type.class)) {
                    log.log(Level.WARNING,
                            String.format("%s.%s: @Type not defined", o.getClass().getName(), field.getName()));
                    Dialogs.show(Alert.AlertType.ERROR, "ReflectiveOperationException", null,
                            String.format("%s.%s: @Type not defined", o.getClass().getName(), field.getName()));
                } else {
                    List<IOEntity> list = (List<IOEntity>) val;
                    Class<? extends IOEntity> type = field.getAnnotation(Type.class).value()
                            .asSubclass(IOEntity.class);
                    TreeItem<Object> listItem = new TreeItem<>(new ListHolder(o, list, field.getName(), type));

                    item.getChildren().add(listItem);

                    listItem.getChildren()
                            .addAll(list.stream().map(Controller::createTreeItem).collect(Collectors.toList()));
                }
            } else if (IOEntity.class.isAssignableFrom(field.getType())) {
                IOEntity ioEntity = (IOEntity) val;

                item.getChildren().add(createTreeItem(ioEntity));
            }
        });
    });
    return item;
}