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.conversantmedia.mapreduce.tool.AnnotatedToolContext.java

@Override
protected void initExtraOptions(Options options) {
    // Find all the fields with @Option annotations...
    fieldsMap = new HashMap<>();
    addedOptionsMap = new HashMap<>();
    defaultValuesMap = new HashMap<>();

    Class<?> clazz = this.bean.getClass();
    while (clazz != Object.class) {
        for (Field field : clazz.getDeclaredFields()) {
            if (field.isAnnotationPresent(Option.class)) {
                Option option = field.getAnnotation(Option.class);
                // Ensure we don't add the same option more than 1x
                // For example, if our annotated bean includes an 'input',
                // we don't want to add a second version
                String optName = getValue(option.name(), field.getName());
                org.apache.commons.cli.Option opt;
                if (options.hasOption(optName)) {
                    opt = options.getOption(optName);
                    updateOption(option, opt);
                } else {
                    opt = initOption(options, option, optName);
                    options.addOption(opt);
                    addedOptionsMap.put(opt.getLongOpt(), field);
                }/* ww w .  ja va 2  s  . co  m*/
                fieldsMap.put(opt.getLongOpt(), field);
                defaultValuesMap.put(opt.getLongOpt(), option.defaultValue());
            }
        }
        clazz = clazz.getSuperclass();
    }
}

From source file:com.design.perpetual.resttodo.app.entities.Todo.java

private Field[] getFields(Todo t) {
    Class<?> cls = t.getClass();
    Field[] fields = cls.getDeclaredFields();
    Field[] supFields = cls.getSuperclass().getDeclaredFields();
    return ArrayUtils.addAll(fields, supFields);
}

From source file:com.glaf.core.util.ReflectUtils.java

private static Object getEmptyObject(Class<?> returnType, Map<Class<?>, Object> emptyInstances, int level) {
    if (level > 2)
        return null;
    if (returnType == null) {
        return null;
    } else if (returnType == boolean.class || returnType == Boolean.class) {
        return false;
    } else if (returnType == char.class || returnType == Character.class) {
        return '\0';
    } else if (returnType == byte.class || returnType == Byte.class) {
        return (byte) 0;
    } else if (returnType == short.class || returnType == Short.class) {
        return (short) 0;
    } else if (returnType == int.class || returnType == Integer.class) {
        return 0;
    } else if (returnType == long.class || returnType == Long.class) {
        return 0L;
    } else if (returnType == float.class || returnType == Float.class) {
        return 0F;
    } else if (returnType == double.class || returnType == Double.class) {
        return 0D;
    } else if (returnType.isArray()) {
        return Array.newInstance(returnType.getComponentType(), 0);
    } else if (returnType.isAssignableFrom(ArrayList.class)) {
        return new java.util.ArrayList<Object>(0);
    } else if (returnType.isAssignableFrom(HashSet.class)) {
        return new HashSet<Object>(0);
    } else if (returnType.isAssignableFrom(HashMap.class)) {
        return new java.util.concurrent.ConcurrentHashMap<Object, Object>(0);
    } else if (String.class.equals(returnType)) {
        return "";
    } else if (!returnType.isInterface()) {
        try {//from  w  w  w.j a v  a2 s.  c om
            Object value = emptyInstances.get(returnType);
            if (value == null) {
                value = returnType.newInstance();
                emptyInstances.put(returnType, value);
            }
            Class<?> cls = value.getClass();
            while (cls != null && cls != Object.class) {
                Field[] fields = cls.getDeclaredFields();
                for (Field field : fields) {
                    Object property = getEmptyObject(field.getType(), emptyInstances, level + 1);
                    if (property != null) {
                        try {
                            if (!field.isAccessible()) {
                                field.setAccessible(true);
                            }
                            field.set(value, property);
                        } catch (Throwable e) {
                        }
                    }
                }
                cls = cls.getSuperclass();
            }
            return value;
        } catch (Throwable e) {
            return null;
        }
    } else {
        return null;
    }
}

From source file:org.neovera.jdiablo.environment.SpringEnvironment.java

private void injectProperties(Object object) {
    Map<String, PropertyPlaceholderProvider> map = _context.getBeansOfType(PropertyPlaceholderProvider.class);
    PropertyPlaceholderProvider ppp = null;
    if (map.size() != 0) {
        ppp = map.values().iterator().next();
    }/*from   w  w  w .  java2s  .  c o  m*/

    // Analyze members to see if they are annotated.
    Map<String, String> propertyNamesByField = new HashMap<String, String>();
    Class<?> clz = object.getClass();
    while (!clz.equals(Object.class)) {
        for (Field field : clz.getDeclaredFields()) {
            if (field.isAnnotationPresent(PropertyPlaceholder.class)) {
                propertyNamesByField.put(
                        field.getName().startsWith("_") ? field.getName().substring(1) : field.getName(),
                        field.getAnnotation(PropertyPlaceholder.class).value());
            }
        }
        clz = clz.getSuperclass();
    }

    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(object.getClass());
    for (PropertyDescriptor pd : descriptors) {
        if (propertyNamesByField.keySet().contains(pd.getName())) {
            if (ppp == null) {
                _logger.error(
                        "Field {} is annotated with PropertyPlaceholder but no bean of type "
                                + "PropertyPlaceholderProvider is defined in the Spring application context.",
                        pd.getName());
                break;
            } else {
                setValue(pd, object, ppp.getProperty(propertyNamesByField.get(pd.getName())));
            }
        } else if (pd.getReadMethod() != null
                && pd.getReadMethod().isAnnotationPresent(PropertyPlaceholder.class)) {
            if (ppp == null) {
                _logger.error(
                        "Field {} is annotated with PropertyPlaceholder but no bean of type "
                                + "PropertyPlaceholderProvider is defined in the Spring application context.",
                        pd.getName());
                break;
            } else {
                setValue(pd, object,
                        ppp.getProperty(pd.getReadMethod().getAnnotation(PropertyPlaceholder.class).value()));
            }
        }
    }
}

From source file:net.ceos.project.poi.annotated.annotation.XlsFreeElementTest.java

/**
 * Test default configuration./*from   w  ww  . ja  v  a2  s  .  co  m*/
 */
@Test
public void checkDefaultConfiguration() {
    Class<XMenFactory.ProfessorX> oC = XMenFactory.ProfessorX.class;

    List<Field> fL = Arrays.asList(oC.getDeclaredFields());
    for (Field f : fL) {
        // Process @XlsFreeElement
        if (f.isAnnotationPresent(XlsFreeElement.class)) {

            XlsFreeElement xlsFreeElement = (XlsFreeElement) f.getAnnotation(XlsFreeElement.class);

            if (f.getName().equals("stringFreeAttribute1")) {
                assertEquals(xlsFreeElement.showTitle(), false);
                assertEquals(xlsFreeElement.titleOrientation(), TitleOrientationType.TOP);
                assertEquals(xlsFreeElement.row(), 1);
                assertEquals(xlsFreeElement.cell(), 1);
                assertEquals(xlsFreeElement.comment(), "");
                assertEquals(xlsFreeElement.commentRules(), "");
                assertEquals(xlsFreeElement.decorator(), "");
                assertEquals(xlsFreeElement.formatMask(), "");
                assertEquals(xlsFreeElement.transformMask(), "");
                assertEquals(xlsFreeElement.isFormula(), false);
                assertEquals(xlsFreeElement.formula(), "");
                assertEquals(xlsFreeElement.customizedRules(), "");
                assertEquals(xlsFreeElement.columnWidthInUnits(), 0);
            }
        }
    }
}

From source file:edu.utah.further.core.xml.jaxb.ToParameterMapJaxbBuilder.java

/**
 * Append all properties of the object to the parameter map using reflection.
 * //from  w  w w .  j a v a2  s .  c  o m
 * @param namePrefix
 *            string to prefix object parameter name with
 * @param obj
 *            object to serialize
 */
private void appendAllFieldsUsingReflection(final String namePrefix, final Object obj) {
    final Class<?> clazz = obj.getClass();
    final Field[] fields = clazz.getDeclaredFields();
    AccessibleObject.setAccessible(fields, true);
    final String parentPrefix = isBlank(namePrefix) ? EMPTY_STRING : (namePrefix + PROPERTY_SCOPE_CHAR);
    try {
        for (final Field field : fields) {
            final Object fieldValue = field.get(obj);
            final XmlElement xmlElement = field.getAnnotation(XmlElement.class);
            if (xmlElement != null) {
                // Add field to map with a proper parameter name
                // final String xmlName = xmlElement.name();
                // final String propertyName = (xmlName == null) ? field.getName()
                // : xmlName;

                // Important: for now, we ignore JAXB names and use the field names,
                // for consistency with Spring's data binder. In the future, if we
                // find an efficient way to alias property names (recursively, for the
                // whole object graph) in Spring, we can use the code commented above
                // so that the XML binding is taken from the JAXB annotation's "name"
                // attribute.
                final String propertyName = field.getName();
                appendFieldUsingReflection(parentPrefix + propertyName, fieldValue);
            }
        }
    } catch (final Throwable e) {
        throw new IllegalStateException("Could not serialize object into a parameter map", e);
    }
}

From source file:com.haulmont.cuba.gui.CompanionDependencyInjector.java

private List<Field> getAllFields(List<Class> classes) {
    List<Field> list = new ArrayList<>();

    for (Class c : classes) {
        if (c != Object.class) {
            for (Field field : c.getDeclaredFields()) {
                int idx = indexOfFieldWithSameName(list, field);
                if (idx > -1)
                    list.set(idx, field);
                else
                    list.add(field);//from  w w w . j  a  va2s  .  c  om
            }
        }
    }
    return list;
}

From source file:org.testng.spring.test.AbstractDependencyInjectionSpringContextTests.java

private void initManagedVariableNames() throws IllegalAccessException {
    LinkedList managedVarNames = new LinkedList();
    Class clazz = getClass();

    do {// w  w  w . j ava  2 s  . c  om
        Field[] fields = clazz.getDeclaredFields();
        if (logger.isDebugEnabled()) {
            logger.debug("Found " + fields.length + " fields on " + clazz);
        }

        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            field.setAccessible(true);
            if (logger.isDebugEnabled()) {
                logger.debug("Candidate field: " + field);
            }
            if (isProtectedInstanceField(field)) {
                Object oldValue = field.get(this);
                if (oldValue == null) {
                    managedVarNames.add(field.getName());
                    if (logger.isDebugEnabled()) {
                        logger.debug("Added managed variable '" + field.getName() + "'");
                    }
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Rejected managed variable '" + field.getName() + "'");
                    }
                }
            }
        }
        clazz = clazz.getSuperclass();
    } while (!clazz.equals(AbstractDependencyInjectionSpringContextTests.class));

    this.managedVariableNames = (String[]) managedVarNames.toArray(new String[managedVarNames.size()]);
}

From source file:com.db2eshop.governance.UIBinder.java

/**
 * <p>create.</p>/*from   w w  w .j  ava 2s  .  com*/
 *
 * @param entityClazz a {@link java.lang.Class} object.
 * @return a {@link java.util.Map} object.
 */
public Map<String, LabeledForm<?>> create(Class<? extends AbstractModel<?>> entityClazz) {
    Map<String, LabeledForm<?>> ui = new HashMap<String, LabeledForm<?>>();

    Field[] fields = entityClazz.getDeclaredFields();
    for (Field field : fields) {
        String fieldName = field.getName();
        if (field.getAnnotation(UIHide.class) != null) {
            continue;
        }
        UIBind uiBind = field.getAnnotation(UIBind.class);
        UIEmbedded uiEmbedded = field.getAnnotation(UIEmbedded.class);
        if (uiBind != null && uiEmbedded == null) {
            Class<? extends LabeledForm<?>> inputClazz = uiBind.value();
            if (inputClazz != null) {
                try {
                    LabeledForm<?> input = ClassUtil.newInstance(inputClazz);
                    input.setLabel(StringUtil.nominilize(fieldName));
                    ui.put(fieldName, input);
                } catch (RuntimeException e) {
                    log.error("Could not instantiate: " + inputClazz.getName(), e);
                }
            } else {
                log.error("No bound LabeledInput found on: " + entityClazz.getName() + "#" + fieldName);
            }
        } else if (uiBind == null && uiEmbedded != null) {
            Class<?> clazz = field.getType();
            if (!AbstractModel.class.isAssignableFrom(clazz)) {
                log.error("Property " + entityClazz.getName() + "#" + fieldName
                        + " is forced to be embedded entity but not assignable to AbstractModel. Skipping.");
            } else {
                AbstractDao<?> daoToBeSet = tableValueEntityResolver.getDao(clazz);
                EntityForm input = new EntityForm(daoToBeSet);
                input.setLabel(StringUtil.nominilize(fieldName));
                ui.put(fieldName, input);
            }
        } else {
            if (uiBind != null && uiEmbedded != null) {
                log.error("Property " + entityClazz.getName() + "#" + fieldName
                        + " is forced to be embedded and bound. Skipping.");
            } else {
                log.debug("Property " + entityClazz.getName() + "#" + fieldName + " not forced to be bound.");
            }
        }
    }
    return ui;
}

From source file:org.ivan.service.ExcelExporter.java

public List<String> getHeaders(Class classDefinition) {

    List<String> fieldNames = new ArrayList<>();

    for (Field field : classDefinition.getDeclaredFields()) {
        fieldNames.add(field.getName());
    }/*from   w  w  w. j  av  a2  s  . co  m*/

    return fieldNames;
}