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:com.nova.geracao.portfolio.BlogServlet.java

private Object getInstanceFromPropertiesMap(Entity entity, Class<?> klass) {
    Object result = null;/*  w ww .ja va2s  .  co m*/
    try {
        Field[] fields = klass.getDeclaredFields();
        result = klass.newInstance();
        for (int i = 0; i < fields.length; i++) {
            if (entity.hasProperty(fields[i].getName())) {
                fields[i].setAccessible(true);
                Object value = entity.getProperty(fields[i].getName());
                if (!ClassUtils.isAssignable(fields[i].getType(), BaseDataClass.class)) {
                    fields[i].set(result, value);
                } else {
                    Object embedValue = getInstanceFromPropertiesMap((EmbeddedEntity) value,
                            fields[i].getType());
                    fields[i].set(result, embedValue);
                }
            }
        }

        Field fieldId = klass.getDeclaredField("id");
        fieldId.setAccessible(true);
        fieldId.set(result, entity.getKey().getId());
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:com.nova.geracao.portfolio.BlogServlet.java

private Object getInstanceFromPropertiesMap(EmbeddedEntity entity, Class<?> klass) {
    Object result = null;//from   w ww. j  av  a  2s  .  c o  m
    try {
        Field[] fields = klass.getDeclaredFields();
        result = klass.newInstance();
        for (int i = 0; i < fields.length; i++) {
            if (entity.hasProperty(fields[i].getName())) {
                fields[i].setAccessible(true);
                Object value = entity.getProperty(fields[i].getName());
                if (!ClassUtils.isAssignable(fields[i].getType(), BaseDataClass.class)) {
                    fields[i].set(result, value);
                } else {
                    Object embedValue = getInstanceFromPropertiesMap((EmbeddedEntity) value,
                            fields[i].getType());
                    fields[i].set(result, embedValue);
                }
            }
        }

        Field fieldId = klass.getDeclaredField("id");
        fieldId.setAccessible(true);
        fieldId.set(result, entity.getKey().getId());
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:com.epam.ta.reportportal.database.search.CriteriaMap.java

private void lookupClass(Class<?> clazz, List<Field> parents) {
    for (Field f : clazz.getDeclaredFields()) {
        if (f.isAnnotationPresent(FilterCriteria.class)) {
            boolean dynamicNestedFields = isDynamicInnerFields(f);
            String searchCriteria;
            String queryCriteria;
            if (of(f.getType().getDeclaredFields()).anyMatch(df -> df.isAnnotationPresent(FilterCriteria.class))
                    || (f.getType().isAnnotationPresent(Document.class)
                            && !f.isAnnotationPresent(DBRef.class))) {
                List<Field> currentParents = new ArrayList<>(parents);
                searchCriteria = parents.isEmpty() ? getSearchCriteria(f)
                        : getSearchCriteria(f, currentParents);
                queryCriteria = parents.isEmpty() ? getQueryCriteria(f) : getQueryCriteria(f, currentParents);
                classCriteria.put(searchCriteria, new CriteriaHolder(searchCriteria, queryCriteria,
                        getDataType(f), f.isAnnotationPresent(DBRef.class), dynamicNestedFields));
                currentParents.add(f);//from w ww.jav  a  2s.  c o m
                lookupClass(f.getType(), currentParents);
            } else {
                searchCriteria = getSearchCriteria(f);
                queryCriteria = getQueryCriteria(f);
                if (parents.isEmpty()) {
                    classCriteria.put(searchCriteria, new CriteriaHolder(searchCriteria, queryCriteria,
                            getDataType(f), f.isAnnotationPresent(DBRef.class), dynamicNestedFields));
                } else {
                    searchCriteria = getSearchCriteria(f, parents);
                    queryCriteria = getQueryCriteria(f, parents);
                    classCriteria.put(getSearchCriteria(f, parents), new CriteriaHolder(searchCriteria,
                            queryCriteria, getDataType(f), false, dynamicNestedFields));
                }
            }
        }
    }
}

From source file:com.changhong.util.db.util.sql.UpdateSqlBuilder.java

/**
 * Where?//ww  w.j  a  v  a 2 s. co  m
 * 
 * @param entity
 * @return
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 * @throws CHDBException
 */
public CHArrayList buildWhere(Object entity)
        throws IllegalArgumentException, IllegalAccessException, CHDBException {
    Class<?> clazz = entity.getClass();
    CHArrayList whereArrayList = new CHArrayList();
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        field.setAccessible(true);
        if (!DBUtils.isTransient(field)) {
            if (DBUtils.isBaseDateType(field)) {
                Annotation annotation = field.getAnnotation(CHPrimaryKey.class);
                if (annotation != null) {
                    String columnName = DBUtils.getColumnByField(field);
                    whereArrayList.add(
                            (columnName != null && !columnName.equals("")) ? columnName : field.getName(),
                            field.get(entity).toString());
                }

            }
        }
    }
    if (whereArrayList.isEmpty()) {
        throw new CHDBException("?Where??");
    }
    return whereArrayList;
}

From source file:com.ge.apm.service.data.DataService.java

private Map<String, String> getFields(Class<?> table) {
    Field[] fields = table.getDeclaredFields();
    Map<String, String> map = new TreeMap<String, String>();
    for (int i = 0; i < fields.length; i++) {
        Column column = fields[i].getAnnotation(Column.class);
        if (column == null)
            continue;
        map.put(fields[i].getName(), column.name());
    }/*from   w w  w . j  a  va 2 s  .c  om*/
    return map;
}

From source file:com.microsoft.windowsazure.mobileservices.MobileServiceTableBase.java

/**
* Returns the system properties defined or annotated in the entity class
* @param   clazz   Target entity class/*from  w  w w.jav a 2s  .  c o  m*/
* @return          List of entities
*/
protected static <F> EnumSet<MobileServiceSystemProperty> getSystemProperties(Class<F> clazz) {
    EnumSet<MobileServiceSystemProperty> result = EnumSet.noneOf(MobileServiceSystemProperty.class);

    Class<?> idClazz = getIdPropertyClass(clazz);

    if (idClazz != null && !isIntegerClass(idClazz)) {
        // Search for system properties annotations, regardless case
        for (Field field : clazz.getDeclaredFields()) {
            SerializedName serializedName = field.getAnnotation(SerializedName.class);

            if (serializedName != null) {
                if (SystemPropertyNameToEnum.containsKey(serializedName.value())) {
                    result.add(SystemPropertyNameToEnum.get(serializedName.value()));
                }
            } else {
                if (SystemPropertyNameToEnum.containsKey(field.getName())) {
                    result.add(SystemPropertyNameToEnum.get(field.getName()));
                }
            }
        }
    }

    // Otherwise, return empty
    return result;
}

From source file:com.dotosoft.dot4command.commands.CallTemplateCommand.java

private void modifyKeyMap(Command newTemp) {
    ModifierHandler modifier = new ModifierHandler() {
        StrSubstitutor sub;/*from w  w  w.java  2s.  c  o  m*/

        @Override
        public void modifier(Object... params) {
            Command valueCommand = (Command) params[0];
            Map valuesMap = (Map) params[1];
            sub = new StrSubstitutor(valuesMap);
            modifyField(valueCommand);
        }

        private void modifyField(Command valueCommand) {
            List<Field> allFields = listAllFields(valueCommand);
            for (Field field : allFields) {
                try {
                    Object value = getProperty(valueCommand, field.getName());
                    if (value instanceof String) {
                        setProperty(valueCommand, field.getName(), sub.replace(value));
                    }
                } catch (Exception ex) {
                }
            }

            if (valueCommand instanceof ChainBase) {
                ChainBase chainBase = (ChainBase) valueCommand;
                List<Command<K, V, C>> listOfCommands = chainBase.getCommands();
                for (Command comm : listOfCommands) {
                    modifyField(comm);
                }
            }
        }

        private List<Field> listAllFields(Object objReflection) {
            List<Field> fieldList = new ArrayList<Field>();
            Class tmpClass = objReflection.getClass();
            while (tmpClass != null) {
                fieldList.addAll(Arrays.asList(tmpClass.getDeclaredFields()));
                tmpClass = tmpClass.getSuperclass();
            }
            return fieldList;
        }
    };

    newTemp.modify(modifier, newTemp, keyMap);
}

From source file:com.grandhunterman.dnvm.common.Message.java

@Override
public final void fromBytes(ByteBuf buf) {
    try {//from  ww w  . j a  va2 s  .  c  om
        Class<?> clazz = getClass();
        for (Field f : clazz.getDeclaredFields()) {
            Class<?> type = f.getType();
            if (acceptField(f, type))
                readField(f, type, buf);
        }
    } catch (Exception e) {
        throw new RuntimeException("Error at reading packet " + this, e);
    }
}

From source file:com.grandhunterman.dnvm.common.Message.java

@Override
public final void toBytes(ByteBuf buf) {
    try {/*  w  w w  .jav  a2  s . c  o  m*/
        Class<?> clazz = getClass();
        for (Field f : clazz.getDeclaredFields()) {
            Class<?> type = f.getType();
            if (acceptField(f, type))
                writeField(f, type, buf);
        }
    } catch (Exception e) {
        throw new RuntimeException("Error at writing packet " + this, e);
    }
}

From source file:com.netflix.spinnaker.halyard.config.validate.v1.FieldValidator.java

private void validateFieldForSpinnakerVersion(ConfigProblemSetBuilder p, Node n) {
    DeploymentConfiguration deploymentConfiguration = n.parentOfType(DeploymentConfiguration.class);
    String spinnakerVersion = deploymentConfiguration.getVersion();
    if (spinnakerVersion == null) {
        return;/*from   w w w.ja v a2 s. c o  m*/
    }

    Class clazz = n.getClass();
    while (clazz != Object.class) {
        Class finalClazz = clazz;
        Arrays.stream(clazz.getDeclaredFields()).forEach(field -> {
            ValidForSpinnakerVersion annotation = field.getDeclaredAnnotation(ValidForSpinnakerVersion.class);
            try {
                field.setAccessible(true);
                Object v = field.get(n);
                boolean fieldNotValid = false;
                String invalidFieldMessage = "";
                String remediation = "";
                if (v != null && annotation != null) {
                    if (Versions.lessThan(spinnakerVersion, annotation.lowerBound())) {
                        fieldNotValid = true;
                        invalidFieldMessage = annotation.tooLowMessage();
                        remediation = "Use at least " + annotation.lowerBound()
                                + " (It may not have been released yet).";
                    } else if (!StringUtils.equals(annotation.upperBound(), "")
                            && Versions.greaterThanEqual(spinnakerVersion, annotation.upperBound())) {
                        fieldNotValid = true;
                        invalidFieldMessage = annotation.tooHighMessage();
                        remediation = "You no longer need this.";
                    }
                }

                // If the field was set to false, it's assumed it's not enabling a restricted feature
                if (fieldNotValid && (v instanceof Boolean) && !((Boolean) v)) {
                    fieldNotValid = false;
                }

                // If the field is a collection, it may be empty
                if (fieldNotValid && (v instanceof Collection) && ((Collection) v).isEmpty()) {
                    fieldNotValid = false;
                }

                if (fieldNotValid) {
                    p.addProblem(Problem.Severity.WARNING,
                            "Field " + finalClazz.getSimpleName() + "." + field.getName()
                                    + " not supported for Spinnaker version " + spinnakerVersion + ": "
                                    + invalidFieldMessage)
                            .setRemediation(remediation);
                }
            } catch (NumberFormatException /* Probably using nightly build */ e) {
                log.info("Nightly builds do not contain version information.");
            } catch (IllegalAccessException /* Probably shouldn't happen */ e) {
                log.warn("Error validating field " + finalClazz.getSimpleName() + "." + field.getName() + ": ",
                        e);
            }
        });
        clazz = clazz.getSuperclass();
    }
}