Example usage for java.lang.reflect Field getName

List of usage examples for java.lang.reflect Field getName

Introduction

In this page you can find the example usage for java.lang.reflect Field getName.

Prototype

public String getName() 

Source Link

Document

Returns the name of the field represented by this Field object.

Usage

From source file:org.agiso.core.i18n.util.I18nUtils.java

public static String getCode(Field f) {
    if (f.isAnnotationPresent(I18n.class)) {
        if (f.getAnnotation(I18n.class).value().length() > 0) {
            return f.getAnnotation(I18n.class).value();
        } else {/*from w  ww. ja v  a 2s.  c o  m*/
            return f.getDeclaringClass().getName() + CODE_SEPARATOR + f.getName();
        }
    }
    // else if(f.isAnnotationPresent(I18nRef.class)) {
    //    Object ref = f.getAnnotation(I18nRef.class).value();
    //    if(((Class<?>)ref).isEnum()) {
    //       return getCode((Enum<?>)ref);
    //    } else {
    //       return getCode((Class<?>)ref);
    //    }
    // }
    return f.getDeclaringClass().getName() + CODE_SEPARATOR + f.getName();
}

From source file:com.impetus.kundera.utils.KunderaCoreUtils.java

/**
 * Prepares composite key as a lucene key.
 * /*from  ww  w .j a va  2 s  . c o m*/
 * @param m
 *            entity metadata
 * @param metaModel
 *            meta model.
 * @param compositeKey
 *            composite key instance
 * @return redis key
 */
public static String prepareCompositeKey(final SingularAttribute attribute, final MetamodelImpl metaModel,
        final Object compositeKey) {
    Field[] fields = attribute.getBindableJavaType().getDeclaredFields();
    EmbeddableType embeddable = metaModel.embeddable(attribute.getBindableJavaType());
    StringBuilder stringBuilder = new StringBuilder();

    try {
        for (Field f : fields) {
            if (!ReflectUtils.isTransientOrStatic(f)) {
                if (metaModel.isEmbeddable(
                        ((AbstractAttribute) embeddable.getAttribute(f.getName())).getBindableJavaType())) {
                    f.setAccessible(true);
                    stringBuilder.append(
                            prepareCompositeKey((SingularAttribute) embeddable.getAttribute(f.getName()),
                                    metaModel, f.get(compositeKey)))
                            .append(LUCENE_COMPOSITE_KEY_SEPERATOR);
                } else {
                    String fieldValue = PropertyAccessorHelper.getString(compositeKey, f);
                    fieldValue = fieldValue.replaceAll("[^a-zA-Z0-9]", "_");

                    stringBuilder.append(fieldValue);
                    stringBuilder.append(LUCENE_COMPOSITE_KEY_SEPERATOR);
                }
            }
        }
    } catch (IllegalAccessException e) {
        logger.error(e.getMessage());
    } catch (IllegalArgumentException e) {
        logger.error("Error during prepare composite key, Caused by {}.", e);
        throw new PersistenceException(e);
    }

    if (stringBuilder.length() > 0) {
        stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(LUCENE_COMPOSITE_KEY_SEPERATOR));
    }
    return stringBuilder.toString();
}

From source file:com.evolveum.midpoint.prism.marshaller.PrismBeanInspector.java

public static String findEnumFieldValueUncached(Class classType, String toStringValue) {
    for (Field field : classType.getDeclaredFields()) {
        XmlEnumValue xmlEnumValue = field.getAnnotation(XmlEnumValue.class);
        if (xmlEnumValue != null && field.getName().equals(toStringValue)) {
            return xmlEnumValue.value();
        }//from   ww w. j  a v a  2 s.  c  om
    }
    return null;
}

From source file:cn.afterturn.easypoi.util.PoiPublicUtil.java

/**
 * //from w w w  .j av a  2 s .c  o m
 *
 * @param clazz
 * @return
 */
public static Object createObject(Class<?> clazz, String targetId) {
    Object obj = null;
    try {
        if (clazz.equals(Map.class)) {
            return new LinkedHashMap<String, Object>();
        }
        obj = clazz.newInstance();
        Field[] fields = getClassFields(clazz);
        for (Field field : fields) {
            if (isNotUserExcelUserThis(null, field, targetId)) {
                continue;
            }
            if (isCollection(field.getType())) {
                ExcelCollection collection = field.getAnnotation(ExcelCollection.class);
                PoiReflectorUtil.fromCache(clazz).setValue(obj, field.getName(),
                        collection.type().newInstance());
            } else if (!isJavaClass(field) && !field.getType().isEnum()) {
                PoiReflectorUtil.fromCache(clazz).setValue(obj, field.getName(),
                        createObject(field.getType(), targetId));
            }
        }

    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new RuntimeException("");
    }
    return obj;

}

From source file:com.astamuse.asta4d.util.annotation.AnnotatedPropertyUtil.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private static AnnotatedPropertyInfoMap retrievePropertiesMap(Class cls) {
    String cacheKey = cls.getName();
    AnnotatedPropertyInfoMap map = propertiesMapCache.get(cacheKey);
    if (map == null) {
        List<AnnotatedPropertyInfo> infoList = new LinkedList<>();
        Set<String> beanPropertyNameSet = new HashSet<>();

        Method[] mtds = cls.getMethods();
        for (Method method : mtds) {
            List<Annotation> annoList = ConvertableAnnotationRetriever
                    .retrieveAnnotationHierarchyList(AnnotatedProperty.class, method.getAnnotations());

            if (CollectionUtils.isEmpty(annoList)) {
                continue;
            }//  w  w w. j a  v  a2  s.  co  m

            AnnotatedPropertyInfo info = new AnnotatedPropertyInfo();
            info.setAnnotations(annoList);

            boolean isGet = false;
            boolean isSet = false;
            String propertySuffixe = method.getName();
            if (propertySuffixe.startsWith("set")) {
                propertySuffixe = propertySuffixe.substring(3);
                isSet = true;
            } else if (propertySuffixe.startsWith("get")) {
                propertySuffixe = propertySuffixe.substring(3);
                isGet = true;
            } else if (propertySuffixe.startsWith("is")) {
                propertySuffixe = propertySuffixe.substring(2);
                isSet = true;
            } else {
                String msg = String.format("Method [%s]:[%s] can not be treated as a getter or setter method.",
                        cls.getName(), method.toGenericString());
                throw new RuntimeException(msg);
            }

            char[] cs = propertySuffixe.toCharArray();
            cs[0] = Character.toLowerCase(cs[0]);
            info.setBeanPropertyName(new String(cs));

            AnnotatedProperty ap = (AnnotatedProperty) annoList.get(0);// must by
            String name = ap.name();
            if (StringUtils.isEmpty(name)) {
                name = info.getBeanPropertyName();
            }

            info.setName(name);

            if (isGet) {
                info.setGetter(method);
                info.setType(method.getReturnType());
                String setterName = "set" + propertySuffixe;
                Method setter = null;
                try {
                    setter = cls.getMethod(setterName, method.getReturnType());
                } catch (NoSuchMethodException | SecurityException e) {
                    String msg = "Could not find setter method:[{}({})] in class[{}] for annotated getter:[{}]";
                    logger.warn(msg, new Object[] { setterName, method.getReturnType().getName(), cls.getName(),
                            method.getName() });
                }
                info.setSetter(setter);
            }

            if (isSet) {
                info.setSetter(method);
                info.setType(method.getParameterTypes()[0]);
                String getterName = "get" + propertySuffixe;
                Method getter = null;
                try {
                    getter = cls.getMethod(getterName);
                } catch (NoSuchMethodException | SecurityException e) {
                    String msg = "Could not find getter method:[{}:{}] in class[{}] for annotated setter:[{}]";
                    logger.warn(msg, new Object[] { getterName, method.getReturnType().getName(), cls.getName(),
                            method.getName() });
                }
                info.setGetter(getter);
            }

            infoList.add(info);
            beanPropertyNameSet.add(info.getBeanPropertyName());
        }

        List<Field> list = new ArrayList<>(ClassUtil.retrieveAllFieldsIncludeAllSuperClasses(cls));
        Iterator<Field> it = list.iterator();

        while (it.hasNext()) {
            Field f = it.next();
            List<Annotation> annoList = ConvertableAnnotationRetriever
                    .retrieveAnnotationHierarchyList(AnnotatedProperty.class, f.getAnnotations());
            if (CollectionUtils.isNotEmpty(annoList)) {
                AnnotatedProperty ap = (AnnotatedProperty) annoList.get(0);// must by

                String beanPropertyName = f.getName();
                if (beanPropertyNameSet.contains(beanPropertyName)) {
                    continue;
                }

                String name = ap.name();
                if (StringUtils.isEmpty(name)) {
                    name = f.getName();
                }

                AnnotatedPropertyInfo info = new AnnotatedPropertyInfo();
                info.setAnnotations(annoList);
                info.setBeanPropertyName(beanPropertyName);
                info.setName(name);
                info.setField(f);
                info.setGetter(null);
                info.setSetter(null);
                info.setType(f.getType());
                infoList.add(info);
            }
        }

        map = new AnnotatedPropertyInfoMap(infoList);
        if (Configuration.getConfiguration().isCacheEnable()) {
            propertiesMapCache.put(cacheKey, map);
        }
    }
    return map;
}

From source file:ml.shifu.shifu.container.meta.MetaFactory.java

/**
 * Iterate each property of Object, get the value and validate
 * //from w ww. j  av a 2s . c om
 * @param isGridSearch
 *            - if grid search, ignore validation in train#params as they are set all as list
 * @param ptag
 *            - the prefix of key to search @MetaItem
 * @param obj
 *            - the object to validate
 * @return ValidateResult
 *         If all items are OK, the ValidateResult.status will be true;
 *         Or the ValidateResult.status will be false, ValidateResult.causes will contain the reasons
 * @throws Exception
 *             any exception in validaiton
 */
public static ValidateResult iterateCheck(boolean isGridSearch, String ptag, Object obj) throws Exception {
    ValidateResult result = new ValidateResult(true);
    if (obj == null) {
        return result;
    }

    Class<?> cls = obj.getClass();
    Field[] fields = cls.getDeclaredFields();

    Class<?> parentCls = cls.getSuperclass();
    if (!parentCls.equals(Object.class)) {
        Field[] pfs = parentCls.getDeclaredFields();
        fields = (Field[]) ArrayUtils.addAll(fields, pfs);
    }

    for (Field field : fields) {
        if (!field.isSynthetic() && !Modifier.isStatic(field.getModifiers()) && !isJsonIngoreField(field)) {
            Method method = cls.getMethod("get" + getMethodName(field.getName()));
            Object value = method.invoke(obj);

            encapsulateResult(result,
                    validate(isGridSearch, ptag + ITEM_KEY_SEPERATOR + field.getName(), value));
        }
    }

    return result;
}

From source file:com.espertech.esper.util.PopulateUtil.java

public static void populateObject(String operatorName, int operatorNum, String dataFlowName,
        Map<String, Object> objectProperties, Object top, EngineImportService engineImportService,
        EPDataFlowOperatorParameterProvider optionalParameterProvider,
        Map<String, Object> optionalParameterURIs) throws ExprValidationException {
    Class applicableClass = top.getClass();
    Set<WriteablePropertyDescriptor> writables = PropertyHelper.getWritableProperties(applicableClass);
    Set<Field> annotatedFields = JavaClassHelper.findAnnotatedFields(top.getClass(), DataFlowOpParameter.class);
    Set<Method> annotatedMethods = JavaClassHelper.findAnnotatedMethods(top.getClass(),
            DataFlowOpParameter.class);

    // find catch-all methods
    Set<Method> catchAllMethods = new LinkedHashSet<Method>();
    if (annotatedMethods != null) {
        for (Method method : annotatedMethods) {
            DataFlowOpParameter anno = (DataFlowOpParameter) JavaClassHelper
                    .getAnnotations(DataFlowOpParameter.class, method.getDeclaredAnnotations()).get(0);
            if (anno.all()) {
                if (method.getParameterTypes().length == 2 && method.getParameterTypes()[0] == String.class
                        && method.getParameterTypes()[1] == Object.class) {
                    catchAllMethods.add(method);
                    continue;
                }/*from  w w w .  j av a2 s .c om*/
                throw new ExprValidationException("Invalid annotation for catch-call");
            }
        }
    }

    // map provided values
    for (Map.Entry<String, Object> property : objectProperties.entrySet()) {
        boolean found = false;
        String propertyName = property.getKey();

        // invoke catch-all setters
        for (Method method : catchAllMethods) {
            try {
                method.invoke(top, new Object[] { propertyName, property.getValue() });
            } catch (IllegalAccessException e) {
                throw new ExprValidationException("Illegal access invoking method for property '" + propertyName
                        + "' for class " + applicableClass.getName() + " method " + method.getName(), e);
            } catch (InvocationTargetException e) {
                throw new ExprValidationException("Exception invoking method for property '" + propertyName
                        + "' for class " + applicableClass.getName() + " method " + method.getName() + ": "
                        + e.getTargetException().getMessage(), e);
            }
            found = true;
        }

        if (propertyName.toLowerCase().equals(CLASS_PROPERTY_NAME)) {
            continue;
        }

        // use the writeable property descriptor (appropriate setter method) from writing the property
        WriteablePropertyDescriptor descriptor = findDescriptor(applicableClass, propertyName, writables);
        if (descriptor != null) {
            Object coerceProperty = coerceProperty(propertyName, applicableClass, property.getValue(),
                    descriptor.getType(), engineImportService, false);

            try {
                descriptor.getWriteMethod().invoke(top, new Object[] { coerceProperty });
            } catch (IllegalArgumentException e) {
                throw new ExprValidationException("Illegal argument invoking setter method for property '"
                        + propertyName + "' for class " + applicableClass.getName() + " method "
                        + descriptor.getWriteMethod().getName() + " provided value " + coerceProperty, e);
            } catch (IllegalAccessException e) {
                throw new ExprValidationException("Illegal access invoking setter method for property '"
                        + propertyName + "' for class " + applicableClass.getName() + " method "
                        + descriptor.getWriteMethod().getName(), e);
            } catch (InvocationTargetException e) {
                throw new ExprValidationException("Exception invoking setter method for property '"
                        + propertyName + "' for class " + applicableClass.getName() + " method "
                        + descriptor.getWriteMethod().getName() + ": " + e.getTargetException().getMessage(),
                        e);
            }
            continue;
        }

        // find the field annotated with {@link @GraphOpProperty}
        for (Field annotatedField : annotatedFields) {
            DataFlowOpParameter anno = (DataFlowOpParameter) JavaClassHelper
                    .getAnnotations(DataFlowOpParameter.class, annotatedField.getDeclaredAnnotations()).get(0);
            if (anno.name().equals(propertyName) || annotatedField.getName().equals(propertyName)) {
                Object coerceProperty = coerceProperty(propertyName, applicableClass, property.getValue(),
                        annotatedField.getType(), engineImportService, true);
                try {
                    annotatedField.setAccessible(true);
                    annotatedField.set(top, coerceProperty);
                } catch (Exception e) {
                    throw new ExprValidationException(
                            "Failed to set field '" + annotatedField.getName() + "': " + e.getMessage(), e);
                }
                found = true;
                break;
            }
        }
        if (found) {
            continue;
        }

        throw new ExprValidationException("Failed to find writable property '" + propertyName + "' for class "
                + applicableClass.getName());
    }

    // second pass: if a parameter URI - value pairs were provided, check that
    if (optionalParameterURIs != null) {
        for (Field annotatedField : annotatedFields) {
            try {
                annotatedField.setAccessible(true);
                String uri = operatorName + "/" + annotatedField.getName();
                if (optionalParameterURIs.containsKey(uri)) {
                    Object value = optionalParameterURIs.get(uri);
                    annotatedField.set(top, value);
                    if (log.isDebugEnabled()) {
                        log.debug("Found parameter '" + uri + "' for data flow " + dataFlowName + " setting "
                                + value);
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Not found parameter '" + uri + "' for data flow " + dataFlowName);
                    }
                }
            } catch (Exception e) {
                throw new ExprValidationException(
                        "Failed to set field '" + annotatedField.getName() + "': " + e.getMessage(), e);
            }
        }

        for (Method method : annotatedMethods) {
            DataFlowOpParameter anno = (DataFlowOpParameter) JavaClassHelper
                    .getAnnotations(DataFlowOpParameter.class, method.getDeclaredAnnotations()).get(0);
            if (anno.all()) {
                if (method.getParameterTypes().length == 2 && method.getParameterTypes()[0] == String.class
                        && method.getParameterTypes()[1] == Object.class) {
                    for (Map.Entry<String, Object> entry : optionalParameterURIs.entrySet()) {
                        String[] elements = URIUtil.parsePathElements(URI.create(entry.getKey()));
                        if (elements.length < 2) {
                            throw new ExprValidationException("Failed to parse URI '" + entry.getKey()
                                    + "', expected " + "'operator_name/property_name' format");
                        }
                        if (elements[0].equals(operatorName)) {
                            try {
                                method.invoke(top, new Object[] { elements[1], entry.getValue() });
                            } catch (IllegalAccessException e) {
                                throw new ExprValidationException(
                                        "Illegal access invoking method for property '" + entry.getKey()
                                                + "' for class " + applicableClass.getName() + " method "
                                                + method.getName(),
                                        e);
                            } catch (InvocationTargetException e) {
                                throw new ExprValidationException(
                                        "Exception invoking method for property '" + entry.getKey()
                                                + "' for class " + applicableClass.getName() + " method "
                                                + method.getName() + ": " + e.getTargetException().getMessage(),
                                        e);
                            }
                        }
                    }
                }
            }
        }
    }

    // third pass: if a parameter provider is provided, use that
    if (optionalParameterProvider != null) {

        for (Field annotatedField : annotatedFields) {
            try {
                annotatedField.setAccessible(true);
                Object provided = annotatedField.get(top);
                Object value = optionalParameterProvider.provide(new EPDataFlowOperatorParameterProviderContext(
                        operatorName, annotatedField.getName(), top, operatorNum, provided, dataFlowName));
                if (value != null) {
                    annotatedField.set(top, value);
                }
            } catch (Exception e) {
                throw new ExprValidationException(
                        "Failed to set field '" + annotatedField.getName() + "': " + e.getMessage(), e);
            }
        }
    }
}

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]);// w ww.j  av  a 2s  .  c  o  m
        }
        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.twinsoft.convertigo.beans.CheckBeans.java

private static void analyzeJavaClass(String javaClassName) {
    try {/*from w w w  .ja  va  2  s  . com*/
        Class<?> javaClass = Class.forName(javaClassName);
        String javaClassSimpleName = javaClass.getSimpleName();

        if (!DatabaseObject.class.isAssignableFrom(javaClass)) {
            //Error.NON_DATABASE_OBJECT.add(javaClassName);
            return;
        }

        nBeanClass++;

        String dboBeanInfoClassName = javaClassName + "BeanInfo";
        MySimpleBeanInfo dboBeanInfo = null;
        try {
            dboBeanInfo = (MySimpleBeanInfo) (Class.forName(dboBeanInfoClassName)).newInstance();
        } catch (ClassNotFoundException e) {
            if (!Modifier.isAbstract(javaClass.getModifiers())) {
                Error.MISSING_BEAN_INFO
                        .add(javaClassName + " (expected bean info: " + dboBeanInfoClassName + ")");
            }
            return;
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        BeanDescriptor beanDescriptor = dboBeanInfo.getBeanDescriptor();

        // Check abstract class
        if (Modifier.isAbstract(javaClass.getModifiers())) {
            // Check icon (16x16)
            String declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo,
                    MySimpleBeanInfo.ICON_COLOR_16x16);
            if (declaredIconName != null) {
                Error.ABSTRACT_CLASS_WITH_ICON.add(javaClassName);
            }

            // Check icon (32x32)
            declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_32x32);
            if (declaredIconName != null) {
                Error.ABSTRACT_CLASS_WITH_ICON.add(javaClassName);
            }

            // Check display name
            if (!beanDescriptor.getDisplayName().equals("?")) {
                Error.ABSTRACT_CLASS_WITH_DISPLAY_NAME.add(javaClassName);
            }

            // Check description
            if (!beanDescriptor.getShortDescription().equals("?")) {
                Error.ABSTRACT_CLASS_WITH_DESCRIPTION.add(javaClassName);
            }
        } else {
            nBeanClassNotAbstract++;

            // Check bean declaration in database_objects.xml
            if (!dboXmlDeclaredDatabaseObjects.contains(javaClassName)) {
                Error.BEAN_DEFINED_BUT_NOT_USED.add(javaClassName);
            }

            // Check icon name policy (16x16)
            String declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo,
                    MySimpleBeanInfo.ICON_COLOR_16x16);
            String expectedIconName = javaClassName.replace(javaClassSimpleName,
                    "images/" + javaClassSimpleName);
            expectedIconName = "/" + expectedIconName.replace('.', '/') + "_color_16x16";
            expectedIconName = expectedIconName.toLowerCase() + ".png";
            if (declaredIconName != null) {
                if (!declaredIconName.equals(expectedIconName)) {
                    Error.BEAN_ICON_NAMING_POLICY.add(javaClassName + "\n" + "      Declared: "
                            + declaredIconName + "\n" + "      Expected: " + expectedIconName);
                }
            }

            // Check icon file (16x16)
            File iconFile = new File(srcBase + declaredIconName);
            if (!iconFile.exists()) {
                Error.BEAN_MISSING_ICON.add(javaClassName + " - icon missing: " + declaredIconName);
            } else {
                icons.remove(declaredIconName);
            }

            // Check icon name policy (32x32)
            declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_32x32);
            expectedIconName = javaClassName.replace(javaClassSimpleName, "images/" + javaClassSimpleName);
            expectedIconName = "/" + expectedIconName.replace('.', '/') + "_color_32x32";
            expectedIconName = expectedIconName.toLowerCase() + ".png";
            if (declaredIconName != null) {
                if (!declaredIconName.equals(expectedIconName)) {
                    Error.BEAN_ICON_NAMING_POLICY.add(javaClassName + "\n" + "      Declared: "
                            + declaredIconName + "\n" + "      Expected: " + expectedIconName);
                }
            }

            // Check icon file (32x32)
            iconFile = new File(srcBase + declaredIconName);
            if (!iconFile.exists()) {
                Error.BEAN_MISSING_ICON.add(javaClassName + " - icon missing: " + declaredIconName);
            } else {
                icons.remove(declaredIconName);
            }

            // Check display name
            if (beanDescriptor.getDisplayName().equals("?")) {
                Error.BEAN_MISSING_DISPLAY_NAME.add(javaClassName);
            }

            // Check description
            if (beanDescriptor.getShortDescription().equals("?")) {
                Error.BEAN_MISSING_DESCRIPTION.add(javaClassName);
            }
        }

        // Check declared bean properties
        PropertyDescriptor[] propertyDescriptors = dboBeanInfo.getLocalPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            String propertyName = propertyDescriptor.getName();
            try {
                javaClass.getDeclaredField(propertyName);
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                try {
                    // Try to find it in the upper classes
                    javaClass.getField(propertyName);
                } catch (SecurityException e1) {
                    // printStackTrace();
                } catch (NoSuchFieldException e1) {
                    Error.PROPERTY_DECLARED_BUT_NOT_FOUND.add(javaClassName + ": " + propertyName);
                }
            }
        }

        Method[] methods = javaClass.getDeclaredMethods();
        List<Method> listMethods = Arrays.asList(methods);
        List<String> listMethodNames = new ArrayList<String>();
        for (Method method : listMethods) {
            listMethodNames.add(method.getName());
        }

        Field[] fields = javaClass.getDeclaredFields();

        for (Field field : fields) {
            int fieldModifiers = field.getModifiers();

            // Ignore static fields (constants)
            if (Modifier.isStatic(fieldModifiers))
                continue;

            String fieldName = field.getName();

            String errorMessage = javaClassName + ": " + field.getName();

            // Check bean info
            PropertyDescriptor propertyDescriptor = isBeanProperty(fieldName, dboBeanInfo);
            if (propertyDescriptor != null) {
                // Check bean property name policy
                if (!propertyDescriptor.getName().equals(fieldName)) {
                    Error.PROPERTY_NAMING_POLICY.add(errorMessage);
                }

                String declaredGetter = propertyDescriptor.getReadMethod().getName();
                String declaredSetter = propertyDescriptor.getWriteMethod().getName();

                String formattedFieldName = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
                String expectedGetter = "get" + formattedFieldName;
                String expectedSetter = "set" + formattedFieldName;

                // Check getter name policy
                if (!declaredGetter.equals(expectedGetter)) {
                    Error.GETTER_SETTER_DECLARED_EXPECTED_NAMES_MISMATCH
                            .add(errorMessage + "\n" + "      Declared getter: " + declaredGetter + "\n"
                                    + "      Expected getter: " + expectedGetter);
                }

                // Check setter name policy
                if (!declaredSetter.equals(expectedSetter)) {
                    Error.GETTER_SETTER_DECLARED_EXPECTED_NAMES_MISMATCH
                            .add(errorMessage + "\n" + "      Declared setter: " + declaredSetter + "\n"
                                    + "      Expected setter: " + expectedSetter);
                }

                // Check required private modifiers for bean property
                if (!Modifier.isPrivate(fieldModifiers)) {
                    Error.PROPERTY_NOT_PRIVATE.add(errorMessage);
                }

                // Check getter
                if (!listMethodNames.contains(declaredGetter)) {
                    Error.GETTER_SETTER_DECLARED_BUT_NOT_FOUND
                            .add(errorMessage + " - Declared getter not found: " + declaredGetter);
                }

                // Check setter
                if (!listMethodNames.contains(declaredSetter)) {
                    Error.GETTER_SETTER_DECLARED_BUT_NOT_FOUND
                            .add(errorMessage + " - Declared setter not found: " + declaredGetter);
                }

                // Check non transient modifier
                if (Modifier.isTransient(fieldModifiers)) {
                    Error.PROPERTY_TRANSIENT.add(errorMessage);
                }
            } else if (!Modifier.isTransient(fieldModifiers)) {
                Error.FIELD_NOT_TRANSIENT.add(errorMessage);
            }
        }
    } catch (ClassNotFoundException e) {
        System.out.println("ERROR on " + javaClassName);
        e.printStackTrace();
    }
}

From source file:com.spectralogic.ds3contractcomparator.print.utils.HtmlRowGeneratorUtils.java

/**
 * Retrieves the specified property of type {@link ImmutableList}
 *//*from  www  . j  ava  2s.com*/
public static <T, N> ImmutableList<N> getListPropertyFromObject(final Field field, final T object) {
    if (object == null) {
        return ImmutableList.of();
    }
    try {
        field.setAccessible(true);
        final Object objectField = field.get(object);
        if (objectField == null) {
            return ImmutableList.of();
        }
        if (objectField instanceof ImmutableList) {
            return (ImmutableList<N>) objectField;
        }
        throw new IllegalArgumentException(
                "Object should be of type ImmutableList, but was: " + object.getClass().toString());
    } catch (final IllegalAccessException e) {
        LOG.error("Could not retrieve list element " + field.getName() + " from object of class "
                + object.getClass().toString() + ": " + e.getMessage(), e);

        return ImmutableList.of();
    }
}