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.l2jfree.util.Introspection.java

private static boolean writeFields(Class<?> c, Object accessor, StringBuilder dest, String eol, boolean init) {
    if (c == null)
        throw new IllegalArgumentException("No class specified.");
    else if (!c.isInstance(accessor))
        throw new IllegalArgumentException(accessor + " is not a " + c.getCanonicalName());
    for (Field f : c.getDeclaredFields()) {
        int mod = f.getModifiers();
        if (Modifier.isStatic(mod))
            continue;
        if (init)
            init = false;/*from   w w  w. j  a  v a 2 s .  c o m*/
        else if (eol == null)
            dest.append(", ");
        String fieldName = null;
        final Column column = f.getAnnotation(Column.class);
        if (column != null)
            fieldName = column.name();
        if (StringUtils.isEmpty(fieldName))
            fieldName = f.getName();
        dest.append(fieldName);
        dest.append(" = ");
        try {
            f.setAccessible(true);
            Object val = f.get(accessor);
            if (accessor == val)
                dest.append("this");
            else
                deepToString(val, dest, null);
        } catch (Exception e) {
            dest.append("???");
        } finally {
            try {
                f.setAccessible(false);
            } catch (Exception e) {
                // ignore
            }
        }
        if (eol != null)
            dest.append(eol);
    }
    return !init;
}

From source file:com.alfresco.orm.ORMUtil.java

public static Map<QName, Serializable> getAlfrescoProperty(final AlfrescoORM alfrescoORM)
        throws IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchMethodException,
        InvocationTargetException, InstantiationException {
    List<Field> fields = new ArrayList<Field>();
    ReflectionUtil.getFields(alfrescoORM.getClass(), fields);
    Map<QName, Serializable> retVal = new HashMap<QName, Serializable>(fields.size());
    for (Field field : fields) {
        if (!field.isAnnotationPresent(SetProperty.class)) {
            if (field.isAnnotationPresent(AlfrescoQName.class)
                    && !field.isAnnotationPresent(AlfrescoAssociation.class)) {
                AlfrescoQName alfrescoQName = field.getAnnotation(AlfrescoQName.class);
                QName qName = QName.createQName(alfrescoQName.namespaceURI(), alfrescoQName.localName());
                Method getterMethod = ReflectionUtil.getMethod(alfrescoORM.getClass(), field.getName());
                retVal.put(qName, (Serializable) getterMethod.invoke(alfrescoORM));
            } else if (field.isAnnotationPresent(AlfrescoAspect.class)) {
                Method getterMethod = ReflectionUtil.getMethod(alfrescoORM.getClass(), field.getName());
                AlfrescoORM aspect = (AlfrescoORM) getterMethod.invoke(alfrescoORM);
                if (null != aspect) {
                    retVal.putAll(getAlfrescoProperty(aspect));
                }//  w  w w.j  av  a 2 s . com
            }
        }
    }
    return retVal;
}

From source file:edu.usu.sdl.openstorefront.core.util.EntityUtil.java

/**
 * Compares to object of the same type/*from   w  w  w . ja v  a 2s.com*/
 *
 * @param original
 * @param compare
 * @param consumeFieldsOnly
 * @return True is different, false if the same
 */
public static boolean isObjectsDifferent(Object original, Object compare, boolean consumeFieldsOnly) {
    boolean changed = false;

    if (original != null && compare == null) {
        changed = true;
    } else if (original == null && compare != null) {
        changed = true;
    } else if (original != null && compare != null) {
        if (original.getClass().isInstance(compare)) {
            List<Field> fields = getAllFields(original.getClass());
            for (Field field : fields) {
                boolean check = true;
                if (consumeFieldsOnly) {
                    ConsumeField consume = (ConsumeField) field.getAnnotation(ConsumeField.class);
                    if (consume == null) {
                        check = false;
                    }
                }
                if (check) {
                    try {
                        changed = isFieldsDifferent(BeanUtils.getProperty(original, field.getName()),
                                BeanUtils.getProperty(compare, field.getName()));
                        if (changed) {
                            break;
                        }
                    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
                        throw new OpenStorefrontRuntimeException("Can't compare object types", ex);
                    }
                }
            }
        } else {
            throw new OpenStorefrontRuntimeException("Can't compare different object types", "Check objects");
        }
    }
    return changed;
}

From source file:jp.co.ctc_g.jfw.core.util.Beans.java

/**
 * ???//from  w ww .  j  a v a2s .c  om
 * @param clazz 
 * @return ??
 */
public static String[] listPseudoPropertyNames(Class<?> clazz) {
    List<String> names = new ArrayList<String>();
    for (PropertyDescriptor pd : Beans.findPropertyDescriptorsFor(clazz)) {
        names.add(pd.getName());
    }
    for (Field f : clazz.getFields()) {
        String n = f.getName();
        if (!names.contains(n))
            names.add(n);
    }
    return names.toArray(new String[0]);
}

From source file:br.com.lucasisrael.regra.reflections.TratamentoReflections.java

/**
 * Attempt to find a {@link Field field} on the supplied {@link Class} with the
 * supplied {@code name} and/or {@link Class type}. Searches all superclasses
 * up to {@link Object}.//w  ww.ja  v a 2 s  .com
 * @param clazz the class to introspect
 * @param name the name of the field (may be {@code null} if type is specified)
 * @param type the type of the field (may be {@code null} if name is specified)
 * @return the corresponding Field object, or {@code null} if not found
 */
public static Field findField(Class<?> clazz, String name, Class<?> type) {
    Assert.notNull(clazz, "Class must not be null");
    Assert.isTrue(name != null || type != null, "Either name or type of the field must be specified");
    Class<?> searchType = clazz;
    while (!Object.class.equals(searchType) && searchType != null) {
        Field[] fields = searchType.getDeclaredFields();
        for (Field field : fields) {
            if ((name == null || name.equals(field.getName()))
                    && (type == null || type.equals(field.getType()))) {
                return field;
            }
        }
        searchType = searchType.getSuperclass();
    }
    return null;
}

From source file:Dumper.java

/**
 * Predicate to determine if a given field is worth being printed. This
 * method could be overridden to reflect customized policy.
 *
 * @param field the field at stake/*from  w  w  w .  ja va 2 s  .  c o  m*/
 *
 * @return true if found relevant
 */
public static boolean isFieldRelevant(Field field) {
    // We don't print static field since the Dumper is meant for instances
    if (Modifier.isStatic(field.getModifiers())) {
        return false;
    }

    // We don't print non-user visible entities
    if (field.getName().indexOf('$') != -1) {
        return false;
    }

    return true;
}

From source file:net.sourceforge.stripes.integration.spring.SpringHelper.java

/**
 * Fetches the fields on a class that are annotated with SpringBean. The first time it
 * is called for a particular class it will introspect the class and cache the results.
 * All non-overridden fields are examined, including protected and private fields.
 * If a field is not public an attempt it made to make it accessible - if it fails
 * it is removed from the collection and an error is logged.
 *
 * @param clazz the class on which to look for SpringBean annotated fields
 * @return the collection of methods with the annotation
 *///from  w w w  .  j  a v a2s. c om
protected static Collection<Field> getFields(Class<?> clazz) {
    Collection<Field> fields = fieldMap.get(clazz);
    if (fields == null) {
        fields = ReflectUtil.getFields(clazz);
        Iterator<Field> iterator = fields.iterator();

        while (iterator.hasNext()) {
            Field field = iterator.next();
            if (!field.isAnnotationPresent(SpringBean.class)) {
                iterator.remove();
            } else if (!field.isAccessible()) {
                // If the field isn't public, try to make it accessible
                try {
                    field.setAccessible(true);
                } catch (SecurityException se) {
                    throw new StripesRuntimeException("Field " + clazz.getName() + "." + field.getName()
                            + "is marked " + "with @SpringBean and is not public. An attempt to call "
                            + "setAccessible(true) resulted in a SecurityException. Please "
                            + "either make the field public, annotate a public setter instead "
                            + "or modify your JVM security policy to allow Stripes to "
                            + "setAccessible(true).", se);
                }
            }
        }

        fieldMap.put(clazz, fields);
    }

    return fields;
}

From source file:br.gov.frameworkdemoiselle.ldap.internal.ClazzUtils.java

/**
 * Get a field name (object attribute name) or the value of @Name if
 * annotation is present. In other words, if @Name is present returns
 * field.getAnnotation(Name.class).value(), otherwise field.getName();
 * //from  w  ww  .  j  a va 2 s.com
 * @param field
 * @return @Name annotation value or object attribute name;
 */
public static String getFieldName(Field field) {
    if (field.isAnnotationPresent(Name.class)) {
        String name = field.getAnnotation(Name.class).value();
        if (name == null || name.trim().isEmpty())
            throw new EntryException("Annotation @Name must have a value");
        return name;
    } else
        return field.getName();
}

From source file:net.ostis.sc.memory.SCKeynodesBase.java

private static boolean checkKeynodeURI(SCSession session, Field field)
        throws IllegalArgumentException, IllegalAccessException {
    KeynodeURI keynodeURI = field.getAnnotation(KeynodeURI.class);

    if (keynodeURI != null) {
        String[] comp = URIUtils.splitByIdtf(keynodeURI.value());

        SCSegment segment = session.openSegment(comp[0]);

        SCAddr keynode = session.findByIdtf(comp[1], segment);
        Validate.notNull(keynode);//from ww w. j  a  v  a  2  s . co  m

        field.set(null, keynode);

        if (log.isDebugEnabled())
            log.debug(keynodeURI.value() + " --> " + field.getName());

        return true;
    } else {
        return false;
    }
}

From source file:com.hurence.logisland.util.kura.Metrics.java

public static <T> T readFrom(final T object, final Map<String, Object> metrics) {
    Objects.requireNonNull(object);

    for (final Field field : FieldUtils.getFieldsListWithAnnotation(object.getClass(), Metric.class)) {
        final Metric m = field.getAnnotation(Metric.class);
        final boolean optional = field.isAnnotationPresent(Optional.class);

        final Object value = metrics.get(m.value());
        if (value == null && !optional) {
            throw new IllegalArgumentException(
                    String.format("Field '%s' is missing metric '%s'", field.getName(), m.value()));
        }/*  w  ww . ja  va2  s  .c  o  m*/

        if (value == null) {
            // not set but optional
            continue;
        }

        try {
            FieldUtils.writeField(field, object, value, true);
        } catch (final IllegalArgumentException e) {
            // provide a better message
            throw new IllegalArgumentException(String.format("Failed to assign '%s' (%s) to field '%s'", value,
                    value.getClass().getName(), field.getName()), e);
        } catch (final IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    for (final Method method : MethodUtils.getMethodsListWithAnnotation(object.getClass(), Metric.class)) {
        final Metric m = method.getAnnotation(Metric.class);
        final boolean optional = method.isAnnotationPresent(Optional.class);

        final Object value = metrics.get(m.value());
        if (value == null && !optional) {
            throw new IllegalArgumentException(
                    String.format("Method '%s' is missing metric '%s'", method.getName(), m.value()));
        }

        if (value == null) {
            // not set but optional
            continue;
        }

        try {
            method.invoke(object, value);
        } catch (final IllegalArgumentException e) {
            // provide a better message
            throw new IllegalArgumentException(String.format("Failed to call '%s' (%s) with method '%s'", value,
                    value.getClass().getName(), method.getName()), e);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    return object;
}