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:com.zlfun.framework.excel.ExcelUtils.java

public static <T> List<String> genItemFieldHeader(Class<T> clazz) {

    Set<String> set = new HashSet<String>();
    List<String> result = new ArrayList<String>();
    try {/*  ww  w  .j a v  a2 s .  co m*/
        Field[] fs = clazz.getDeclaredFields();
        for (Field f : fs) {

            WebParam itemField = f.getAnnotation(WebParam.class);
            if (itemField == null) {
                continue;
            }
            if ("".equals(itemField.value())) {
                String fname = f.getName();
                if (!set.contains(fname)) {
                    set.add(fname);
                    result.add(fname);
                }
            } else {
                String fname = itemField.value();
                if (!set.contains(fname)) {
                    set.add(fname);
                    result.add(fname);
                }
            }
            // ?
            Class<?> parent = clazz.getSuperclass();
            while (parent != Object.class) {
                parent(parent, set, result);
                parent = parent.getSuperclass();
            }

        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return result;
}

From source file:ch.ralscha.extdirectspring.generator.association.AbstractAssociation.java

public static AbstractAssociation createAssociation(ModelAssociation associationAnnotation, ModelBean model,
        Field field) {
    ModelAssociationType type = associationAnnotation.value();

    Class<?> associationClass = associationAnnotation.model();
    if (associationClass == Object.class) {
        associationClass = field.getType();
    }/* w  ww. j  a  v a2 s.  c  o m*/

    AbstractAssociation association;

    if (type == ModelAssociationType.HAS_MANY) {
        association = new HasManyAssociation(associationClass);
    } else if (type == ModelAssociationType.BELONGS_TO) {
        association = new BelongsToAssociation(associationClass);
    } else {
        association = new HasOneAssociation(associationClass);
    }

    association.setAssociationKey(field.getName());

    if (StringUtils.hasText(associationAnnotation.foreignKey())) {
        association.setForeignKey(associationAnnotation.foreignKey());
    } else if (type == ModelAssociationType.HAS_MANY) {
        association.setForeignKey(StringUtils.uncapitalize(field.getDeclaringClass().getSimpleName()) + "_id");
    } else if (type == ModelAssociationType.BELONGS_TO || type == ModelAssociationType.HAS_ONE) {
        association.setForeignKey(StringUtils.uncapitalize(associationClass.getSimpleName()) + "_id");
    }

    if (StringUtils.hasText(associationAnnotation.primaryKey())) {
        association.setPrimaryKey(associationAnnotation.primaryKey());
    } else if (type == ModelAssociationType.HAS_MANY && StringUtils.hasText(model.getIdProperty())
            && !model.getIdProperty().equals("id")) {
        association.setPrimaryKey(model.getIdProperty());
    } else if (type == ModelAssociationType.BELONGS_TO || type == ModelAssociationType.HAS_ONE) {
        Model associationModelAnnotation = associationClass.getAnnotation(Model.class);
        if (associationModelAnnotation != null && StringUtils.hasText(associationModelAnnotation.idProperty())
                && !associationModelAnnotation.idProperty().equals("id")) {
            association.setPrimaryKey(associationModelAnnotation.idProperty());
        }
    }

    if (type == ModelAssociationType.HAS_MANY) {
        HasManyAssociation hasManyAssociation = (HasManyAssociation) association;

        if (StringUtils.hasText(associationAnnotation.setterName())) {
            LogFactory.getLog(ModelGenerator.class)
                    .warn(getWarningText(field, association.getType(), "setterName"));
        }

        if (StringUtils.hasText(associationAnnotation.getterName())) {
            LogFactory.getLog(ModelGenerator.class)
                    .warn(getWarningText(field, association.getType(), "getterName"));
        }

        if (associationAnnotation.autoLoad()) {
            hasManyAssociation.setAutoLoad(true);
        }
        if (StringUtils.hasText(associationAnnotation.name())) {
            hasManyAssociation.setName(associationAnnotation.name());
        } else {
            hasManyAssociation.setName(field.getName());
        }

    } else if (type == ModelAssociationType.BELONGS_TO) {
        BelongsToAssociation belongsToAssociation = (BelongsToAssociation) association;

        if (StringUtils.hasText(associationAnnotation.setterName())) {
            belongsToAssociation.setSetterName(associationAnnotation.setterName());
        } else {
            belongsToAssociation.setSetterName("set" + StringUtils.capitalize(field.getName()));
        }

        if (StringUtils.hasText(associationAnnotation.getterName())) {
            belongsToAssociation.setGetterName(associationAnnotation.getterName());
        } else {
            belongsToAssociation.setGetterName("get" + StringUtils.capitalize(field.getName()));
        }

        if (associationAnnotation.autoLoad()) {
            LogFactory.getLog(ModelGenerator.class)
                    .warn(getWarningText(field, association.getType(), "autoLoad"));
        }
        if (StringUtils.hasText(associationAnnotation.name())) {
            LogFactory.getLog(ModelGenerator.class).warn(getWarningText(field, association.getType(), "name"));
        }
    } else {
        HasOneAssociation hasOneAssociation = (HasOneAssociation) association;

        if (StringUtils.hasText(associationAnnotation.setterName())) {
            hasOneAssociation.setSetterName(associationAnnotation.setterName());
        } else {
            hasOneAssociation.setSetterName("set" + StringUtils.capitalize(field.getName()));
        }

        if (StringUtils.hasText(associationAnnotation.getterName())) {
            hasOneAssociation.setGetterName(associationAnnotation.getterName());
        } else {
            hasOneAssociation.setGetterName("get" + StringUtils.capitalize(field.getName()));
        }

        if (associationAnnotation.autoLoad()) {
            LogFactory.getLog(ModelGenerator.class)
                    .warn(getWarningText(field, association.getType(), "autoLoad"));
        }
        if (StringUtils.hasText(associationAnnotation.name())) {
            LogFactory.getLog(ModelGenerator.class).warn(getWarningText(field, association.getType(), "name"));
        }
    }

    return association;
}

From source file:com.erudika.para.utils.Utils.java

/**
 * Returns a list of all declared fields in a class. Transient and serialVersionUID fields are skipped.
 * This method scans parent classes as well.
 * @param clazz a class to scan//  w ww  .ja  v a2 s.com
 * @return a list of fields including those of the parent classes excluding the Object class.
 */
public static List<Field> getAllDeclaredFields(Class<? extends ParaObject> clazz) {
    LinkedList<Field> fields = new LinkedList<Field>();
    if (clazz == null) {
        return fields;
    }
    Class<?> parent = clazz;
    do {
        for (Field field : parent.getDeclaredFields()) {
            if (!Modifier.isTransient(field.getModifiers()) && !field.getName().equals("serialVersionUID")) {
                fields.add(field);
            }
        }
        parent = parent.getSuperclass();
    } while (!parent.equals(Object.class));
    return fields;
}

From source file:com.erudika.para.utils.ValidationUtils.java

/**
 * Returns the JSON Node representation of all validation constraints for a single type.
 * @param app the app//from www  .j a v a 2  s. co  m
 * @param type a valid Para data type
 * @return a JSON Node object
 */
public static Map<String, Map<String, Map<String, Object>>> getValidationConstraints(App app, String type) {
    Map<String, Map<String, Map<String, Object>>> fieldsMap = new HashMap<String, Map<String, Map<String, Object>>>();
    if (app != null && !StringUtils.isBlank(type)) {
        try {
            List<Field> fieldlist = Utils.getAllDeclaredFields(Utils.toClass(type));
            for (Field field : fieldlist) {
                Annotation[] annos = field.getAnnotations();
                if (annos.length > 1) {
                    Map<String, Map<String, Object>> consMap = new HashMap<String, Map<String, Object>>();
                    for (Annotation anno : annos) {
                        if (isValidConstraintType(anno.annotationType())) {
                            Constraint c = fromAnnotation(anno);
                            if (c != null) {
                                consMap.put(c.getName(), c.getPayload());
                            }
                        }
                    }
                    if (consMap.size() > 0) {
                        fieldsMap.put(field.getName(), consMap);
                    }
                }
            }
            Map<String, Map<String, Map<String, Object>>> appConstraints = app.getValidationConstraints()
                    .get(type);
            if (appConstraints != null && !appConstraints.isEmpty()) {
                fieldsMap.putAll(appConstraints);
            }
        } catch (Exception ex) {
            logger.error(null, ex);
        }
    }
    return fieldsMap;
}

From source file:com.tugo.dt.PojoUtils.java

private static String getSingleFieldSetterExpression(final Class<?> pojoClass, final String fieldExpression,
        final Class<?> exprClass) {
    JavaStatement code = new JavaStatement(
            pojoClass.getName().length() + fieldExpression.length() + exprClass.getName().length() + 32);
    /* Construct ((<pojo class name>)pojo). */
    code.appendCastToTypeExpr(pojoClass, OBJECT).append(".");
    try {//from www .  j  a  va 2  s.  co m
        final Field field = pojoClass.getField(fieldExpression);
        if (ClassUtils.isAssignable(exprClass, field.getType())) {
            /* there is public field on the class, use direct assignment. */
            /* append <field name> = (<field type>)val; */
            return code.append(field.getName()).append(" = ").appendCastToTypeExpr(exprClass, VAL)
                    .getStatement();
        }
        logger.debug("{} can not be assigned to {}. Proceeding to locate a setter method.", exprClass, field);
    } catch (NoSuchFieldException ex) {
        logger.debug("{} does not have field {}. Proceeding to locate a setter method.", pojoClass,
                fieldExpression);
    } catch (SecurityException ex) {
        logger.debug("{} does not have field {}. Proceeding to locate a setter method.", pojoClass,
                fieldExpression);
    }

    final String setMethodName = SET + upperCaseWord(fieldExpression);
    Method bestMatchMethod = null;
    List<Method> candidates = new ArrayList<Method>();
    for (Method method : pojoClass.getMethods()) {
        if (setMethodName.equals(method.getName())) {
            Class<?>[] parameterTypes = method.getParameterTypes();
            if (parameterTypes.length == 1) {
                if (exprClass == parameterTypes[0]) {
                    bestMatchMethod = method;
                    break;
                } else if (org.apache.commons.lang.ClassUtils.isAssignable(exprClass, parameterTypes[0])) {
                    candidates.add(method);
                }
            }
        }
    }

    if (bestMatchMethod == null) { // We did not find the exact match, use candidates to find the match
        if (candidates.size() == 0) {
            logger.debug("{} does not have suitable setter method {}. Returning original expression {}.",
                    pojoClass, setMethodName, fieldExpression);
            /* We did not find any match at all, use original expression */
            /* append = (<expr type>)val;*/
            return code.append(fieldExpression).append(" = ").appendCastToTypeExpr(exprClass, VAL)
                    .getStatement();
        } else {
            // TODO: see if we can find a better match
            bestMatchMethod = candidates.get(0);
        }
    }

    /* We found a method that we may use for setter */
    /* append <method name>((<expr class)val); */
    return code.append(bestMatchMethod.getName()).append("(").appendCastToTypeExpr(exprClass, VAL).append(")")
            .getStatement();
}

From source file:com.feilong.core.bean.BeanUtil.java

/**
 * ??? klass {@link Alias} , ?? {@link Alias#name()} ?map .
 *
 * @param klass//ww  w .j a va2  s.com
 *            the klass
 * @return <code>klass</code>  {@link Alias} , {@link Collections#emptyMap()}
 * @throws NullPointerException
 *              <code>klass</code> null
 * @since 1.8.1
 */
private static Map<String, String> buildPropertyNameAndAliasMap(Class<?> klass) {
    Validate.notNull(klass, "klass can't be null!");
    List<Field> aliasFieldsList = FieldUtils.getFieldsListWithAnnotation(klass, Alias.class);
    if (isNullOrEmpty(aliasFieldsList)) {
        return emptyMap();
    }
    //??key
    Map<String, String> propertyNameAndAliasMap = newHashMap(aliasFieldsList.size());
    for (Field field : aliasFieldsList) {
        Alias alias = field.getAnnotation(Alias.class);
        propertyNameAndAliasMap.put(field.getName(), alias.name());
    }
    return propertyNameAndAliasMap;
}

From source file:com.qualogy.qafe.business.integration.adapter.MappingAdapter.java

private static Object adaptToJavaObject(String mappingId, String attributeName, Object result,
        Object valueToAdapt, ClassLoader classLoader) {
    try {//from   w w  w.j a va 2s. co  m
        if (valueToAdapt != null) {
            Class resultClazz = classLoader.loadClass(result.getClass().getName());

            Field field = resultClazz.getDeclaredField(attributeName);
            field.setAccessible(true);
            String fieldName = field.getType().getName();
            String valueName = valueToAdapt.getClass().getName();
            logger.info(field.getType().getName());

            if (!fieldName.equals(valueName)) {
                if (PredefinedClassTypeConverter.isPredefined(field.getType()))
                    valueToAdapt = PredefinedAdapterFactory.create(field.getType()).convert(valueToAdapt);
                else
                    throw new IllegalArgumentException("Object passed [" + valueToAdapt
                            + "] cannot be converted to type wanted[" + field.getType() + "] for field["
                            + field.getName() + "] in adapter[" + mappingId + "]");
            } else {
                if (!PredefinedClassTypeConverter.isPredefined(field.getType())) {
                    Class paramClazz = classLoader.loadClass(fieldName);
                    valueToAdapt = paramClazz.cast(valueToAdapt);
                }
            }
            field.set(result, valueToAdapt);
        }
    } catch (IllegalArgumentException e) {
        throw new UnableToAdaptException(
                "arg [" + valueToAdapt + "] is illegal for field with name [" + attributeName + "]", e);
    } catch (SecurityException e) {
        throw new UnableToAdaptException(e);
    } catch (IllegalAccessException e) {
        throw new UnableToAdaptException(
                "field [" + attributeName + "] does not accessible on class [" + result.getClass() + "]", e);
    } catch (NoSuchFieldException e) {
        logger.log(Level.WARNING,
                "field [" + attributeName + "] does not exist on class [" + result.getClass() + "]", e);
    } catch (ClassNotFoundException e) {
        throw new UnableToAdaptException(
                "field [" + attributeName + "] class not found [" + result.getClass() + "]", e);
    }
    return result;
}

From source file:com.intel.xdk.facebook.IntelXDKFacebook.java

public static final int[] getStyleableIntArray(String name) {
    try {//from  ww  w.  j  a v  a2  s  .  com
        Field[] fields2 = Class.forName(sharedContext.getPackageName() + ".R$styleable").getFields();
        for (Field f : fields2) {
            if (f.getName().equals(name)) {
                int[] ret = (int[]) f.get(null);
                return ret;
            }
        }
    } catch (Throwable t) {
    }
    return null;
}

From source file:gov.nih.nci.system.web.util.RESTUtil.java

public static Object getAttribute(Field field, String attributeName, Class rootClass) throws Exception {
    Object attribute = null;// ww w  .  j ava 2s.co  m

    String fieldName = field.getDeclaringClass().getName() + "." + field.getName();
    log.debug("attributeName " + attributeName);
    log.debug("fieldName " + fieldName);
    if (attributeName.equals(fieldName)) {
        attribute = Class.forName(fieldName).newInstance();
        log.debug("Equal returning " + attribute);
        return attribute;
    } else if (attributeName.indexOf(fieldName) == -1)
        throw new Exception("Invalid field and attribute combination.  Field: " + fieldName + " ; attribute:"
                + attributeName);

    String subAttributeName = attributeName.substring(attributeName.indexOf(fieldName) + 1,
            attributeName.length());
    log.debug("subAttributeName " + subAttributeName);

    return attribute;
}