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.google.feedserver.util.CommonsCliHelper.java

/**
 * Loop through each registered class and parse the command line for their
 * flags. If option isnt specified we leave the default.
 *//*from ww  w  .java2s. com*/
@SuppressWarnings("unchecked")
private void populateClasses() {
    for (Class flagClass : classes) {
        for (Field field : flagClass.getFields()) {
            if (field.getName().endsWith("_FLAG")) {
                String argName = field.getName().substring(0, field.getName().length() - "_FLAG".length());
                if (field.getType().getName().equals(Boolean.class.getName())) {
                    if (flags.hasOption(argName)) {
                        setField(field, new Boolean(true));
                    } else if (flags.hasOption("no" + argName)) {
                        setField(field, new Boolean(false));
                    }
                } else {
                    String argValue = flags.getOptionValue(argName, null);
                    if (argValue != null) {
                        setField(field, argValue);
                    }
                }
            }
        }
    }
}

From source file:com.yek.keyboard.ChewbaccaUncaughtExceptionHandler.java

private void addResourceNameWithId(StringBuilder resources, int resourceId, Class clazz) {
    for (Field field : clazz.getFields()) {
        if (field.getType().equals(int.class)) {
            if ((field.getModifiers() & (Modifier.STATIC | Modifier.PUBLIC)) != 0) {
                try {
                    if (resourceId == field.getInt(null)) {
                        resources.append(clazz.getName()).append(".").append(field.getName());
                        resources.append('\n');
                    }//from   w ww  . j  a v a  2s  . c o  m
                } catch (IllegalAccessException e) {
                    Logger.d("EEEE", "Failed to access " + field.getName(), e);
                }
            }
        }
    }
}

From source file:com.fluidops.iwb.api.CommunicationServiceImpl.java

/**
 * lookup field for a given property//from w  w w  . ja  v a 2  s . c  o m
 * @param ifc       the ontology class
 * @param prop      the prop / method name
 * @return          the method getting the prop name
 * @throws NoSuchFieldException
 */
public static Field getField(Class<?> ifc, String prop) throws NoSuchFieldException {
    for (Field field : ifc.getFields()) {
        if (field.getName().equals(prop))
            return field;

        OWLProperty p = AnnotationProcessor.getOWLProperty(ifc, field);
        if (p != null) {
            if (p.propName().equals(prop))
                return field;

            if (EndpointImpl.api().getNamespaceService().guessURIOrCreateInDefaultNS(p.propName())
                    .equals(EndpointImpl.api().getNamespaceService().guessURIOrCreateInDefaultNS(prop)))
                return field;
        }
    }
    return null;
}

From source file:org.querybyexample.jpa.JpaUniqueUtil.java

private Field columnNameToField(Class<?> clazz, String columnName) {
    for (Field field : clazz.getFields()) {
        Column column = field.getAnnotation(Column.class);
        if (equalsIgnoreCase(columnName, column.name())) {
            return field;
        }//from w w w  . ja  v  a 2 s  .co m
    }
    return null;
}

From source file:org.pentaho.reporting.libraries.css.model.StyleKeyRegistry.java

private void registerClass(final Class c) {
    // Log.debug ("Registering stylekeys from " + c);
    try {//from w ww  . j a  va2  s .  c om
        final Field[] fields = c.getFields();
        for (int i = 0; i < fields.length; i++) {
            final Field field = fields[i];
            final int modifiers = field.getModifiers();
            if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)) {
                if (Modifier.isFinal(modifiers) == false) {
                    logger.warn("Invalid implementation: StyleKeys should be 'public static final': " + c);
                }
                if (field.getType().isAssignableFrom(StyleKey.class)) {
                    final StyleKey value = (StyleKey) field.get(null);
                    if (value == null) {
                        logger.warn("Invalid implementation: StyleKeys fields must not be null: " + c);
                    }
                    // ignore the returned value, all we want is to trigger the key
                    // creation
                    // Log.debug ("Loaded key " + value);
                }
            }
        }
    } catch (IllegalAccessException e) {
        // wont happen, we've checked it..
    }
}

From source file:com.activecq.api.ActiveProperties.java

/**
 * Uses reflection to create a List of the keys defined in the ActiveField subclass (and its inheritance tree).
 * Only fields that meet the following criteria are returned:
 * - public/*w  w  w .j  a  v a 2s  . c  o m*/
 * - static
 * - final
 * - String
 * - Upper case 
 * @return a List of all the Fields
 */
@SuppressWarnings("unchecked")
public List<String> getKeys() {
    ArrayList<String> keys = new ArrayList<String>();
    ArrayList<String> names = new ArrayList<String>();
    Class cls = this.getClass();

    if (cls == null) {
        return Collections.unmodifiableList(keys);
    }

    Field fieldList[] = cls.getFields();

    for (Field fld : fieldList) {
        int mod = fld.getModifiers();

        // Only look at public static final fields
        if (!Modifier.isPublic(mod) || !Modifier.isStatic(mod) || !Modifier.isFinal(mod)) {
            continue;
        }

        // Only look at String fields
        if (!String.class.equals(fld.getType())) {
            continue;
        }

        // Only look at uppercase fields
        if (!StringUtils.equals(fld.getName().toUpperCase(), fld.getName())) {
            continue;
        }

        // Get the value of the field
        String value;
        try {
            value = StringUtils.stripToNull((String) fld.get(this));
        } catch (IllegalArgumentException e) {
            continue;
        } catch (IllegalAccessException e) {
            continue;
        }

        // Do not add duplicate or null keys, or previously added named fields
        if (value == null || names.contains(fld.getName()) || keys.contains(value)) {
            continue;
        }

        // Success! Add key to key list
        keys.add(value);

        // Add field named to process field names list
        names.add(fld.getName());

    }

    return Collections.unmodifiableList(keys);
}

From source file:org.polymap.wbv.mdb.MdbEntityImporter.java

public MdbEntityImporter(UnitOfWork uow, Class<T> entityClass) {
    this.uow = uow;
    this.entityClass = entityClass;
    this.tableName = entityClass.getAnnotation(ImportTable.class).value();

    for (Field f : entityClass.getFields()) {
        ImportColumn a = f.getAnnotation(ImportColumn.class);
        if (a != null) {
            fieldMap.put(a.value(), f);/*from   ww w .  j  a v  a2  s.  com*/
        }
    }
}

From source file:org.apache.openjpa.lib.util.Options.java

/**
 * Finds all the options that can be set on the provided class. This does
 * not look for path-traversal expressions.
 *
 * @param type The class for which available options should be listed.
 * @return The available option names in <code>type</code>. The
 * names will have initial caps. They will be ordered alphabetically.
 *//* w w  w  .j  a  v  a2  s.  c  o  m*/
public static Collection<String> findOptionsFor(Class<?> type) {
    Collection<String> names = new TreeSet<String>();
    // look for a setter method matching the key
    Method[] meths = type.getMethods();
    Class<?>[] params;
    for (int i = 0; i < meths.length; i++) {
        if (meths[i].getName().startsWith("set")) {
            params = meths[i].getParameterTypes();
            if (params.length == 0)
                continue;
            if (params[0].isArray())
                continue;

            names.add(StringUtils.capitalize(meths[i].getName().substring(3)));
        }
    }

    // check for public fields
    Field[] fields = type.getFields();
    for (int i = 0; i < fields.length; i++)
        names.add(StringUtils.capitalize(fields[i].getName()));

    return names;
}

From source file:net.eledge.android.toolkit.db.internal.TableBuilder.java

public List<String> createTableUpdates(Class<?> clazz) {
    List<String> updates = new ArrayList<>();
    final List<String> names = getExistingFields(clazz);
    for (Field field : clazz.getFields()) {
        if (field.isAnnotationPresent(Column.class)) {
            String name = SQLBuilder.getFieldName(field);
            if (!names.contains(name)) {
                StringBuilder sb = new StringBuilder("ALTER TABLE ");
                sb.append(SQLBuilder.getTableName(clazz));
                sb.append(" ADD COLUMN ");
                sb.append(createFieldDef(clazz, field));
                sb.append(";");
                updates.add(sb.toString());
            }//  w  ww.  ja va2 s .  c om
        }
    }
    return updates;
}

From source file:microsoft.exchange.webservices.data.core.EwsUtilities.java

/**
 * Builds the enum to schema mapping dictionary.
 *
 * @param c class type/*  w  ww. j a  v a 2s.c om*/
 * @return The mapping from enum to schema name
 */
private static Map<String, String> buildEnumToSchemaDict(Class<?> c) {
    Map<String, String> dict = new HashMap<String, String>();
    Field[] fields = c.getFields();
    for (Field f : fields) {
        if (f.isEnumConstant() && f.isAnnotationPresent(EwsEnum.class)) {
            EwsEnum ewsEnum = f.getAnnotation(EwsEnum.class);
            String fieldName = f.getName();
            String schemaName = ewsEnum.schemaName();
            if (!schemaName.isEmpty()) {
                dict.put(fieldName, schemaName);
            }
        }
    }
    return dict;
}