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:Main.java

/**
 * Attempt to find a {@link Field field} on the supplied {@link Class} with the
 * supplied <code>name</code>. Searches all superclasses up to {@link Object}.
 *
 * @param clazz the class to introspect//from  w w w  .j av a 2 s . co  m
 * @param name  the name of the field
 * @return the corresponding Field object, or <code>null</code> if not found
 */
public static Field findField(Class<?> clazz, String name) {
    Class<?> searchType = clazz;
    while (!Object.class.equals(searchType) && searchType != null) {
        Field[] fields = searchType.getDeclaredFields();
        for (Field field : fields) {
            if (name.equals(field.getName())) {
                field.setAccessible(true);
                return field;
            }
        }
        searchType = searchType.getSuperclass();
    }
    return null;
}

From source file:Main.java

/**
 * Gets all of the fields in this class and the super classes
 *
 * @param beanClass// w  ww. j  av  a  2  s.c o m
 * @return
 */
static private List<Field> getFields(final Class<?> beanClass) {
    // This class must remain private due to Java 2 Security concerns
    List<Field> fields = AccessController.doPrivileged(new PrivilegedAction<List<Field>>() {
        public List<Field> run() {
            List<Field> fields = new ArrayList<Field>();
            Class<?> cls = beanClass;
            while (cls != null) {
                Field[] fieldArray = cls.getDeclaredFields();
                for (Field field : fieldArray) {
                    fields.add(field);
                }
                cls = cls.getSuperclass();
            }
            return fields;
        }
    });

    return fields;
}

From source file:com.hortonworks.registries.common.util.ReflectionHelper.java

/**
 * Given a class, this method returns a map of names of all the instance (non static) fields to type.
 * if the class has any super class it also includes those fields.
 * @param clazz , not null//from   w w  w .  jav a2 s.co m
 * @return
 */
public static Map<String, Class> getFieldNamesToTypes(Class clazz) {
    Field[] declaredFields = clazz.getDeclaredFields();
    Map<String, Class> instanceVariableNamesToTypes = new HashMap<>();
    for (Field field : declaredFields) {
        if (!Modifier.isStatic(field.getModifiers())) {
            LOG.trace("clazz {} has field {} with type {}", clazz.getName(), field.getName(),
                    field.getType().getName());
            instanceVariableNamesToTypes.put(field.getName(), field.getType());
        } else {
            LOG.trace("clazz {} has field {} with type {}, which is static so ignoring", clazz.getName(),
                    field.getName(), field.getType().getName());
        }
    }

    if (!clazz.getSuperclass().equals(Object.class)) {
        instanceVariableNamesToTypes.putAll(getFieldNamesToTypes(clazz.getSuperclass()));
    }
    return instanceVariableNamesToTypes;
}

From source file:Main.java

/**
 * get all fields for a class/*from   w w  w  .  j  av a 2 s.com*/
 *
 * @param type
 * @return all fields indexed by their names
 */
private static Map<String, Field> getAllFields(Class<?> type) {
    Map<String, Field> fields = new HashMap<String, Field>();
    Class<?> currentType = type;
    while (!currentType.equals(Object.class)) {
        for (Field field : currentType.getDeclaredFields()) {
            int mod = field.getModifiers();
            /*
             * by convention, our fields should not have any modifier
             */
            if (mod == 0 || Modifier.isProtected(mod) && !Modifier.isStatic(mod)) {
                fields.put(field.getName(), field);
            }
        }
        currentType = currentType.getSuperclass();
    }
    return fields;
}

From source file:Main.java

/**
 * create a string out of the object fields that are set
 * @param obj Object//from   w  w  w.  j av  a 2  s .c om
 * @return String in Json format.
 * @throws Exception Nitro exception is thrown.
 */
public static String object_to_string(java.lang.Object obj) throws Exception {
    String str = null;

    Class<?> c = obj.getClass();
    Field[] flds = c.getDeclaredFields();
    if (flds != null) {
        for (int i = 0; i < flds.length; i++) {
            flds[i].setAccessible(true);
            if (flds[i].get(obj) != null) {
                String strtmp = "";
                Object tmp = flds[i].get(obj);
                if (flds[i].getType().isArray()) {
                    if (tmp instanceof String[]) {
                        String[] tmp1 = (String[]) tmp;
                        for (int j = 0; j < tmp1.length; j++)
                            strtmp += tmp1[j] + " ";
                    } else if (tmp instanceof Integer[]) {
                        Integer[] tmp1 = (Integer[]) tmp;
                        for (int j = 0; j < tmp1.length; j++)
                            strtmp += tmp1[j].toString() + " ";
                    } else if (tmp instanceof Long[]) {
                        Long[] tmp1 = (Long[]) tmp;
                        for (int j = 0; j < tmp1.length; j++)
                            strtmp += tmp1[j].toString() + " ";
                    } else if (tmp instanceof Double[]) {
                        Double[] tmp1 = (Double[]) tmp;
                        for (int j = 0; j < tmp1.length; j++)
                            strtmp += tmp1[j].toString() + " ";
                    } else if (tmp instanceof Boolean[]) {
                        Boolean[] tmp1 = (Boolean[]) tmp;
                        for (int j = 0; j < tmp1.length; j++)
                            strtmp += tmp1[j].toString() + " ";
                    }
                    strtmp = strtmp.trim();
                } else {
                    strtmp = flds[i].get(obj).toString();
                }
                if (str != null)
                    str = str + ",";
                if (str == null)
                    str = "\"" + flds[i].getName() + "\"" + ":" + "\"" + encode(strtmp) + "\"";
                else
                    str = str + "\"" + flds[i].getName() + "\"" + ":" + "\"" + encode(strtmp) + "\"";
            }
        }
    }
    return str;
}

From source file:Main.java

/**
 * create a string (without quotes)out of the object fields that are set
 * @param obj Object// w ww . j  ava 2 s .  c  o  m
 * @return String in Json format.
 * @throws Exception Nitro exception is thrown.
 */
public static String object_to_string_withoutquotes(java.lang.Object obj) throws Exception {
    String str = null;

    Class<?> c = obj.getClass();
    Field[] flds = c.getDeclaredFields();
    if (flds != null) {
        for (int i = 0; i < flds.length; i++) {
            flds[i].setAccessible(true);
            if (flds[i].get(obj) != null) {
                String strtmp = "";
                if (flds[i].getType().isArray()) {
                    Object tmp = flds[i].get(obj);
                    if (tmp instanceof String[]) {
                        String[] tmp1 = (String[]) tmp;
                        for (int j = 0; j < tmp1.length; j++)
                            strtmp += tmp1[j] + " ";
                    } else if (tmp instanceof Integer[]) {
                        Integer[] tmp1 = (Integer[]) tmp;
                        for (int j = 0; j < tmp1.length; j++)
                            strtmp += tmp1[j].toString() + " ";
                    } else if (tmp instanceof Long[]) {
                        Long[] tmp1 = (Long[]) tmp;
                        for (int j = 0; j < tmp1.length; j++)
                            strtmp += tmp1[j].toString() + " ";
                    } else if (tmp instanceof Double[]) {
                        Double[] tmp1 = (Double[]) tmp;
                        for (int j = 0; j < tmp1.length; j++)
                            strtmp += tmp1[j].toString() + " ";
                    } else if (tmp instanceof Boolean[]) {
                        Boolean[] tmp1 = (Boolean[]) tmp;
                        for (int j = 0; j < tmp1.length; j++)
                            strtmp += tmp1[j].toString() + " ";
                    }
                    strtmp = strtmp.trim();
                } else {
                    strtmp = flds[i].get(obj).toString();
                }
                if (str != null)
                    str = str + ",";
                if (str == null)
                    str = flds[i].getName() + ":" + encode(strtmp);
                else
                    str = str + flds[i].getName() + ":" + encode(strtmp);
            }
        }
    }
    return str;
}

From source file:com.netflix.astyanax.util.StringUtils.java

public static <T> String joinClassAttributeValues(final T object, String name, Class<T> clazz) {
    Field[] fields = clazz.getDeclaredFields();

    StringBuilder sb = new StringBuilder();
    sb.append(name).append("[");
    sb.append(org.apache.commons.lang.StringUtils.join(Collections2.transform(
            // Filter any field that does not start with lower case
            // (we expect constants to start with upper case)
            Collections2.filter(Arrays.asList(fields), new Predicate<Field>() {
                @Override//from  w w  w  . j a  va 2 s  .  c  om
                public boolean apply(Field field) {
                    if ((field.getModifiers() & Modifier.STATIC) == Modifier.STATIC)
                        return false;
                    return Character.isLowerCase(field.getName().charAt(0));
                }
            }),
            // Convert field to "name=value". value=*** on error
            new Function<Field, String>() {
                @Override
                public String apply(Field field) {
                    Object value;
                    try {
                        value = field.get(object);
                    } catch (Exception e) {
                        value = "***";
                    }
                    return field.getName() + "=" + value;
                }
            }), ","));
    sb.append("]");

    return sb.toString();
}

From source file:Main.java

/**
 * Returns all fields declared in the class passed as argument or in its super classes.
 *///  ww  w  . j  a va2s . c o  m
public static List<Field> getAllDeclaredField(Class<?> clazz, boolean includeSuperClass) {
    final List<Field> result = new LinkedList<Field>();
    for (final Field field : clazz.getDeclaredFields()) {
        result.add(field);
    }
    final Class<?> superClass = clazz.getSuperclass();
    if (superClass != null && includeSuperClass) {
        result.addAll(getAllDeclaredField(superClass, true));
    }
    return result;
}

From source file:nu.yona.server.test.util.JUnitUtil.java

public static Field getAccessibleField(Class<?> clazz, String fieldName) {
    Field field = Arrays.asList(clazz.getDeclaredFields()).stream().filter(f -> f.getName().equals(fieldName))
            .findAny().orElseThrow(() -> new IllegalStateException("Cannot find field '" + fieldName + "'"));
    field.setAccessible(true);/*w  ww.j a va 2s.  co m*/
    return field;
}

From source file:com.ms.commons.lang.ObjectUtils.java

/**
 * string?trim?//from   ww w .  j a v a2s  . c om
 * 
 * @param object
 * @throws Exception
 */
private static void trimStringField(Object object, Class<?> clazz) throws Exception {
    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);
            }
        }
    }
}