Example usage for java.lang Class getFields

List of usage examples for java.lang Class getFields

Introduction

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

Prototype

@CallerSensitive
public Field[] getFields() throws SecurityException 

Source Link

Document

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

Usage

From source file:com.jskaleel.xml.JSONObject.java

/**
 * Get an array of field names from an Object.
 *
 * @return An array of field names, or null if there are no names.
 *///from ww w  .  j  a  va  2 s  .  co  m
public static String[] getNames(Object object) {
    if (object == null) {
        return null;
    }
    Class klass = object.getClass();
    Field[] fields = klass.getFields();
    int length = fields.length;
    if (length == 0) {
        return null;
    }
    String[] names = new String[length];
    for (int i = 0; i < length; i += 1) {
        names[i] = fields[i].getName();
    }
    return names;
}

From source file:org.apache.click.service.ClickClickConfigService.java

/**
 * @see org.apache.click.service.ConfigService#getPageFieldArray(java.lang.Class)
 *
 * @param pageClass the page class/*from   www  .j a va  2  s.c  o  m*/
 * @return an array public fields for the given page class
 */
public Field[] getPageFieldArray(Class pageClass) {
    if (isProductionMode() || isProfileMode()) {
        return super.getPageFieldArray(pageClass);
    }
    return pageClass.getFields();
}

From source file:com.github.hateoas.forms.spring.xhtml.XhtmlResourceMessageConverter.java

private void writeObject(XhtmlWriter writer, Object object)
        throws IOException, IllegalAccessException, InvocationTargetException {
    if (!DataType.isSingleValueType(object.getClass())) {
        writer.beginDl();/*w  ww. j  a  va 2 s  .c om*/
    }
    if (object instanceof Map) {
        Map<?, ?> map = (Map<?, ?>) object;
        for (Entry<?, ?> entry : map.entrySet()) {
            String name = entry.getKey().toString();
            Object content = entry.getValue();
            String docUrl = documentationProvider.getDocumentationUrl(name, content);
            writeObjectAttributeRecursively(writer, name, content, docUrl);
        }
    } else if (object instanceof Enum) {
        String name = ((Enum) object).name();
        String docUrl = documentationProvider.getDocumentationUrl(name, object);
        writeDdForScalarValue(writer, object);
    } else if (object instanceof Currency) {
        // TODO configurable classes which should be rendered with toString
        // or use JsonSerializer or DataType?
        String name = object.toString();
        String docUrl = documentationProvider.getDocumentationUrl(name, object);
        writeDdForScalarValue(writer, object);
    } else {
        Class<?> aClass = object.getClass();
        Map<String, PropertyDescriptor> propertyDescriptors = PropertyUtils.getPropertyDescriptors(object);
        // getFields retrieves public only
        Field[] fields = aClass.getFields();
        for (Field field : fields) {
            String name = field.getName();
            if (!propertyDescriptors.containsKey(name)) {
                Object content = field.get(object);
                String docUrl = documentationProvider.getDocumentationUrl(field, content);
                //<a href="http://schema.org/review">http://schema.org/performer</a>
                writeObjectAttributeRecursively(writer, name, content, docUrl);
            }
        }
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors.values()) {
            String name = propertyDescriptor.getName();
            if (FILTER_RESOURCE_SUPPORT.contains(name)) {
                continue;
            }
            Method readMethod = propertyDescriptor.getReadMethod();
            if (readMethod != null) {
                Object content = readMethod.invoke(object);
                String docUrl = documentationProvider.getDocumentationUrl(readMethod, content);
                writeObjectAttributeRecursively(writer, name, content, docUrl);
            }
        }
    }
    if (!DataType.isSingleValueType(object.getClass())) {
        writer.endDl();
    }
}

From source file:org.evosuite.setup.TestClusterGenerator.java

/**
 * Get the set of fields defined in this class and its superclasses
 * /*  www .j  av  a 2  s .  c  o  m*/
 * @param clazz
 * @return
 */
public static Set<Field> getAccessibleFields(Class<?> clazz) {
    Set<Field> fields = new LinkedHashSet<Field>();
    try {
        for (Field f : clazz.getFields()) {
            if (canUse(f) && !Modifier.isFinal(f.getModifiers())) {
                fields.add(f);
            }
        }
    } catch (Throwable t) {
        logger.info("Error while accessing fields of class {} - check allowed permissions: {}", clazz.getName(),
                t);
    }
    return fields;
}

From source file:pico.commons.beans.BeanInfo.java

/**
 * public {@link Field Field}  ./*  w  ww . j  av a 2s. com*/
 * @param cls Class
 */
private void addFields(Class<?> cls) {
    Field[] fields = (isPrivateAccess) ? cls.getDeclaredFields() : cls.getFields();
    fields = ReflectionUtil.normalize(fields);
    for (int i = 0; i < fields.length; i++) {
        if (isPrivateAccess)
            fields[i].setAccessible(true);
        String fieldName = fields[i].getName();
        Class<?> fieldType = fields[i].getType();
        this.fields.put(fieldName, fields[i]);
        fieldTypes.put(fieldName, fieldType);
    }
}

From source file:com.streamsets.datacollector.definition.ConfigDefinitionExtractor.java

private List<ConfigDefinition> getConfigDefinitions(String configPrefix, Class klass, List<String> stageGroups,
        Object contextMsg) {/*from  ww  w  . j  a  v  a 2s. c o  m*/
    List<ConfigDefinition> defs = new ArrayList<>();
    for (Field field : klass.getFields()) {
        if (field.getAnnotation(ConfigDef.class) != null) {
            defs.add(extractConfigDef(configPrefix, stageGroups, field,
                    Utils.formatL("{} Field='{}'", contextMsg, field.getName())));
        } else if (field.getAnnotation(ConfigDefBean.class) != null) {
            List<String> beanGroups = getGroups(field, stageGroups, contextMsg, new ArrayList<ErrorMessage>());
            defs.addAll(extract(configPrefix + field.getName() + ".", field.getType(), beanGroups, true,
                    Utils.formatL("{} BeanField='{}'", contextMsg, field.getName())));
        }
    }
    return defs;
}

From source file:com.googlecode.android_scripting.facade.AndroidFacade.java

@Rpc(description = "Get list of constants (static final fields) for a class")
public Bundle getConstants(
        @RpcParameter(name = "classname", description = "Class to get constants from") String classname)
        throws Exception {
    Bundle result = new Bundle();
    int flags = Modifier.FINAL | Modifier.PUBLIC | Modifier.STATIC;
    Class<?> clazz = Class.forName(classname);
    for (Field field : clazz.getFields()) {
        if ((field.getModifiers() & flags) == flags) {
            Class<?> type = field.getType();
            String name = field.getName();
            if (type == int.class) {
                result.putInt(name, field.getInt(null));
            } else if (type == long.class) {
                result.putLong(name, field.getLong(null));
            } else if (type == double.class) {
                result.putDouble(name, field.getDouble(null));
            } else if (type == char.class) {
                result.putChar(name, field.getChar(null));
            } else if (type instanceof Object) {
                result.putString(name, field.get(null).toString());
            }//from  ww  w .j a  va  2s . c o m
        }
    }
    return result;
}

From source file:org.lman.json.JsonConverter.java

private static Object readJson(Object json, Class<?> clazz, TypeParameter typeParameter)
        throws ReadJsonException, InstantiationException, IllegalAccessException, JSONException,
        IllegalArgumentException, SecurityException, InvocationTargetException, NoSuchMethodException {
    if (json == null || json == JSONObject.NULL) {
        return null;
    } else if (clazz == String.class || clazz == Boolean.class || clazz == Integer.class) {
        return json;
    } else if (clazz == Long.class) {
        // It's a Number but not an Integer, need to convert it into an integer for JSON :(
        return Long.valueOf(((Number) json).longValue());
    } else if (Collection.class.isAssignableFrom(clazz)) {
        return readCollection(json, clazz, typeParameter);
    } else if (clazz.isEnum()) {
        return readEnum(json, clazz);
    } else if (Map.class.isAssignableFrom(clazz)) {
        if (typeParameter == null)
            throw new ReadJsonException("Missing type parameter");
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject jsonObject = (JSONObject) json;
        for (String key : jsonObject.keySet())
            map.put(key, readJson(jsonObject.get(key), typeParameter.value(), null));
        return map;
    } else {/*from   ww w.  j  a  va  2 s  . c  o  m*/
        if (!(json instanceof JSONObject))
            throw new ReadJsonException(
                    json + " not a JSONObject (is " + json.getClass() + " for clazz " + clazz + ")");
        Object object = clazz.newInstance();
        for (Field field : clazz.getFields()) {
            if (Modifier.isStatic(field.getModifiers()))
                continue;

            try {
                Object readObject = readJson(((JSONObject) json).get(field.getName()), field.getType(),
                        field.getAnnotation(TypeParameter.class));
                field.set(object, readObject);
            } catch (JSONException e) {
                // Ok, probably just not found.
            }
        }
        return object;
    }
}

From source file:recite18th.controller.Controller.java

private Hashtable fillParams() {
    try {//from  www.  ja  v  a  2 s  .  c  om
        params = new Hashtable();
        Class cl = Class.forName("application.models._" + modelForm.getPlainClassName());
        //TOFIX: because we use cl.getFields(), all fields neet to be define as public
        Field[] fields = cl.getFields();
        String fieldValue;
        String fieldName;

        // NEXT : Rephrase this
        for (int i = 0; i < fields.length; i++) {
            fieldName = fields[i].getName();
            fieldValue = getFormFieldValue(fieldName);

            if (fieldName.equals(modelForm.getPkFieldName())) {
                modelForm.setPkFieldValue(getFormFieldValue("hidden_" + fieldName));
                Logger.getLogger(Controller.class.getName()).log(Level.INFO,
                        "Putting field primary key from {0} into params", "hidden_" + fieldName);
                params.put("hidden_" + fieldName, getFormFieldValue("hidden_" + fieldName));
            }

            if (fieldValue != null) {
                params.put(fieldName, fieldValue);
                Logger.getLogger(Controller.class.getName()).log(Level.INFO,
                        "Putting field form {0} into params", fieldName);
            }
        }
        return params;
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;

}

From source file:com.ng.mats.psa.mt.paga.data.JSONObject.java

/**
 * Get an array of field names from an Object.
 * /*from  w w w  .j  a v  a  2 s .  c  o  m*/
 * @return An array of field names, or null if there are no names.
 */
public static String[] getNames(Object object) {
    if (object == null) {
        return null;
    }
    Class<?> klass = object.getClass();
    Field[] fields = klass.getFields();
    int length = fields.length;
    if (length == 0) {
        return null;
    }
    String[] names = new String[length];
    for (int i = 0; i < length; i += 1) {
        names[i] = fields[i].getName();
    }
    return names;
}