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:org.blockartistry.lib.ConfigProcessor.java

public static void process(@Nonnull final Configuration config, @Nonnull final Class<?> clazz,
        @Nullable final Object parameters) {
    for (final Field field : clazz.getFields()) {
        final Parameter annotation = field.getAnnotation(Parameter.class);
        if (annotation != null) {
            final String category = annotation.category();
            final String property = annotation.property();
            final String language = annotation.lang();
            final String comment = field.getAnnotation(Comment.class) != null
                    ? field.getAnnotation(Comment.class).value()
                    : "NEEDS COMMENT";

            try {
                final Object defaultValue = field.get(parameters);

                if (defaultValue instanceof Boolean) {
                    field.set(parameters, config.getBoolean(property, category,
                            Boolean.valueOf(annotation.defaultValue()), comment));
                } else if (defaultValue instanceof Integer) {
                    int minInt = Integer.MIN_VALUE;
                    int maxInt = Integer.MAX_VALUE;
                    final MinMaxInt mmi = field.getAnnotation(MinMaxInt.class);
                    if (mmi != null) {
                        minInt = mmi.min();
                        maxInt = mmi.max();
                    }//from w w w. ja v a  2s. c om
                    field.set(parameters, config.getInt(property, category,
                            Integer.valueOf(annotation.defaultValue()), minInt, maxInt, comment));
                } else if (defaultValue instanceof Float) {
                    float minFloat = Float.MIN_VALUE;
                    float maxFloat = Float.MAX_VALUE;
                    final MinMaxFloat mmf = field.getAnnotation(MinMaxFloat.class);
                    if (mmf != null) {
                        minFloat = mmf.min();
                        maxFloat = mmf.max();
                    }
                    field.set(parameters, config.getFloat(property, category,
                            Float.valueOf(annotation.defaultValue()), minFloat, maxFloat, comment));
                } else if (defaultValue instanceof String) {
                    field.set(parameters,
                            config.getString(property, category, annotation.defaultValue(), comment));
                } else if (defaultValue instanceof String[]) {
                    field.set(parameters, config.getStringList(property, category,
                            StringUtils.split(annotation.defaultValue(), ','), comment));
                }

                // Configure other settings
                final Property prop = config.getCategory(category).get(property);
                if (!StringUtils.isEmpty(language))
                    prop.setLanguageKey(language);
                if (field.getAnnotation(RestartRequired.class) != null) {
                    final RestartRequired restart = field.getAnnotation(RestartRequired.class);
                    prop.setRequiresMcRestart(restart.server());
                    prop.setRequiresWorldRestart(restart.world());
                } else {
                    prop.setRequiresMcRestart(false);
                    prop.setRequiresWorldRestart(false);
                }

                prop.setShowInGui(field.getAnnotation(Hidden.class) == null);

            } catch (final Throwable t) {
                LibLog.log().error("Unable to parse configuration", t);
            }
        }
    }
}

From source file:gov.va.vinci.leo.tools.LeoUtils.java

/**
 * Create the set of ConfigurationParameter objects from the Param class of an object.
 *
 * @param c Param class//from  ww w . j  a  va2s . c  om
 * @return Set of ConfigurationParameter objects
 */
public static Set<ConfigurationParameter> getStaticConfigurationParameters(Class c) {
    Set<ConfigurationParameter> list = new HashSet<ConfigurationParameter>();
    Field[] fields = c.getFields();
    for (Field field : fields) {
        try {
            if (field.getType().equals(ConfigurationParameter.class)
                    && Modifier.isStatic(field.getModifiers())) {
                list.add((ConfigurationParameter) field.get(null));
            }
        } catch (IllegalAccessException e) {
            // Handle exception here
        }
    }
    return list;
}

From source file:com.feilong.commons.core.lang.reflect.FieldUtil.java

/**
 * ?? Class ??(public)<br>/*from www  . j  ava 2 s .com*/
 * ??<br>
 * ??? void 0 . <br>
 *  Class ?.<br>
 *  Class ????. <br>
 * .
 * 
 * @param clz
 *            the clz
 * @return the field names
 * @see Class#getFields()
 * @see #getFieldsNames(Field[])
 */
public static String[] getFieldNames(Class<?> clz) {
    Field[] fields = clz.getFields();
    return getFieldsNames(fields);
}

From source file:com.antsdb.saltedfish.sql.ExternalTable.java

public static <T> ExternalTable wrap(Orca orca, String namespace, Class<T> klass, Iterable<T> iterable) {
    ClassBasedTable<T> table = new ClassBasedTable<>();
    table.source = iterable;/*from  w  ww.  ja v  a2s  . c o m*/
    table.meta.setNamespace(namespace).setTableName(iterable.getClass().getSimpleName());
    List<ColumnMeta> columns = new ArrayList<>();
    for (Field i : klass.getFields()) {
        ColumnMeta column = new ColumnMeta(orca.getTypeFactory(), new SlowRow(0));
        column.setColumnName(i.getName()).setId(table.meta.getColumns().size());
        if (i.getType() == String.class) {
            column.setType(DataType.varchar());
        } else if (i.getType() == int.class) {
            column.setType(DataType.integer());
        } else if (i.getType() == long.class) {
            column.setType(DataType.longtype());
        } else {
            throw new NotImplementedException();
        }
        columns.add(column);
        table.fields.add(i);
    }
    table.meta.setColumns(columns);
    return table;
}

From source file:com.aw.support.reflection.MethodInvoker.java

public static List getAttributes(Object target) {
    logger.info("searching attributes " + target.getClass().getName());
    List attributes = new ArrayList();
    List<Field> forms = new ArrayList();
    Class cls = target.getClass();
    Field[] fields = cls.getFields();
    for (int i = 0; i < fields.length; i++) {
        if ((fields[i].getName().startsWith("txt") || fields[i].getName().startsWith("chk"))
                && !fields[i].getName().startsWith("chkSel")) {
            attributes.add(fields[i]);//from w ww  .j  ava 2 s.c  om
        }
        if ((fields[i].getType().getSimpleName().startsWith("Frm"))) {
            forms.add(fields[i]);
        }
    }
    if (forms.size() > 0) {
        for (Field field : forms) {
            try {
                Object formToBeChecked = field.get(target);
                if (formToBeChecked != null) {
                    List formAttributes = getAttributes(formToBeChecked);
                    if (formAttributes.size() > 0) {
                        attributes.addAll(formAttributes);
                    }
                } else {
                    logger.warn("FRM NULL:" + field.getName());
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                throw new AWSystemException("Problems getting value for:<" + field.getName() + ">", e);
            }
        }
    }
    return attributes;
}

From source file:com.Da_Technomancer.crossroads.API.packets.Message.java

private static Field[] getClassFields(Class<?> clazz) {
    if (fieldCache.containsValue(clazz))
        return fieldCache.get(clazz);
    else {// www. j  av a  2s. c  o m
        Field[] fields = clazz.getFields();
        Arrays.sort(fields, (Field f1, Field f2) -> {
            return f1.getName().compareTo(f2.getName());
        });
        fieldCache.put(clazz, fields);
        return fields;
    }
}

From source file:it.nicola_amatucci.util.Json.java

public static <T> T object_from_json(JSONObject json, Class<T> objClass) throws Exception {
    T t = null;/*from   w w  w  .  java2 s.  c  o  m*/
    Object o = null;

    try {
        //create new object instance
        t = objClass.newInstance();

        //object fields
        Field[] fields = objClass.getFields();

        for (Field field : fields) {
            //field name
            o = json.get(field.getName());

            if (o.equals(null))
                continue;

            //field value
            try {
                String typeName = field.getType().getSimpleName();

                if (typeName.equals("String")) {
                    o = json.getString(field.getName()); //String
                } else if (typeName.equals("boolean")) {
                    o = Integer.valueOf(json.getInt(field.getName())); //boolean
                } else if (typeName.equals("int")) {
                    o = Integer.valueOf(json.getInt(field.getName())); //int
                } else if (typeName.equals("long")) {
                    o = Long.valueOf(json.getLong(field.getName())); //long                  
                } else if (typeName.equals("double")) {
                    o = Double.valueOf(json.getDouble(field.getName())); //double
                } else if (typeName.equals("Date")) {
                    o = new SimpleDateFormat(Json.DATA_FORMAT).parse(o.toString()); //data
                } else if (field.getType().isArray()) {
                    JSONArray arrayJSON = new JSONArray(o.toString());
                    T[] arrayOfT = (T[]) null;

                    try {
                        //create object array
                        Class c = Class.forName(field.getType().getName()).getComponentType();
                        arrayOfT = (T[]) Array.newInstance(c, arrayJSON.length());

                        //parse objects                  
                        for (int i = 0; i < json.length(); i++)
                            arrayOfT[i] = (T) object_from_json(arrayJSON.getJSONObject(i), c);
                    } catch (Exception e) {
                        throw e;
                    }

                    o = arrayOfT;
                } else {
                    o = object_from_json(new JSONObject(o.toString()), field.getType()); //object
                }

            } catch (Exception e) {
                throw e;
            }

            t.getClass().getField(field.getName()).set(t, o);
        }

    } catch (Exception e) {
        throw e;
    }

    return t;
}

From source file:wwutil.sys.ReflectUtil.java

/** Find the field of the class having the annotation defined on it.
 *//*from   www .ja  v  a 2  s.  c o  m*/
public static Field findAnnotatedField(Class clazz, Class fieldAnnClass) {
    for (Field field : clazz.getFields()) {
        Object annObj = field.getAnnotation(fieldAnnClass);
        if (annObj != null)
            return field;
    }
    return null;
}

From source file:com.jilk.ros.rosbridge.implementation.JSON.java

private static Message convertJSONArrayToMessage(JSONArray ja, Class c, Registry<Class> r) {
    try {//from  w  w w  .  jav  a 2  s. com
        Message result = (Message) c.newInstance();
        int arrayIndex = 0;
        for (Field f : c.getFields()) {
            Class fc = getFieldClass(result, null, f, r);
            Object lookup = ja.get(arrayIndex++); // yes we are assuming that the fields are delivered in order
            if (lookup != null) {
                Object value = convertElementToField(lookup, fc, f, r);
                f.set(result, value);
            }
        }

        return result;
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:com.eviware.x.form.support.ADialogBuilder.java

private static void buildForm(XFormDialogBuilder builder, String name, Class<?> formClass,
        MessageSupport messages) {//w ww.  j  a v a 2 s.  co m
    XForm form = builder.createForm(name);
    for (Field formField : formClass.getFields()) {
        AField formFieldAnnotation = formField.getAnnotation(AField.class);
        if (formFieldAnnotation != null) {
            try {
                addFormField(form, formField, formFieldAnnotation, messages);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}