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.siberhus.ngai.core.CrudHelper.java

@SuppressWarnings("unchecked")
public final static List<Object> findByExample(EntityManager em, Class<?> entityClass, Object example) {
    if (em == null) {
        throw new IllegalArgumentException("EntityManager is null");
    }/*from ww  w  .ja  v a 2 s.co m*/
    EntityInfo entityInfo = getEntityInfo(entityClass);
    List<Object> params = new ArrayList<Object>();
    StringBuilder sql = new StringBuilder(255);
    sql.append("from ").append(entityInfo.getEntityName()).append(" e where 1=1 ");
    try {
        for (Field field : entityInfo.getFieldSet()) {
            sql.append("and e.").append(field.getName()).append("=? ");
            params.add(field.get(example));
        }
    } catch (IllegalAccessException e) {
        throw new NgaiRuntimeException("Unable to get field value from example model: " + example, e);
    }
    Query query = em.createQuery(sql.toString());
    for (int i = 0; i < params.size(); i++) {
        query.setParameter(i + 1, params.get(i));
    }
    return query.getResultList();
}

From source file:com.spectralogic.ds3contractcomparator.print.htmlprinter.generators.row.ModifiedHtmlRowGenerator.java

/**
 * Recursively traverses two objects using reflection and constructs the modified
 * rows that represent the changes and differences between the objects.
 *///from  w  ww  .  ja  v  a 2 s.c om
public static <T> ImmutableList<Row> createModifiedRows(final T oldObject, final T newObject,
        final int indent) {
    if (oldObject == null && newObject == null) {
        return ImmutableList.of();
    }
    final Field[] fields = getFields(oldObject, newObject);
    final ImmutableList.Builder<Row> builder = ImmutableList.builder();

    for (final Field field : fields) {
        final String property = field.getName();

        final Optional<String> oldValue = getPropertyValue(oldObject, property);
        final Optional<String> newValue = getPropertyValue(newObject, property);

        if (oldValue.isPresent() || newValue.isPresent()) {
            final int fieldIndent = toModifiedFieldIndent(indent, oldObject, newObject, field);
            if (field.getType() == ImmutableList.class) {
                //Field is a list, recursively print each element in the list
                builder.add(new NoChangeRow(fieldIndent, property, ""));

                final ImmutableList<Object> oldObjList = getListPropertyFromObject(field, oldObject);
                final ImmutableList<Object> newObjList = getListPropertyFromObject(field, newObject);

                if (hasContent(oldObjList) || hasContent(newObjList)) {
                    final String uniqueProperty = getPropertyNameFromList(oldObjList, newObjList);

                    final ImmutableSet<String> parameterUnion = toPropertyUnion(oldObjList, newObjList,
                            uniqueProperty);
                    final ImmutableMap<String, Object> oldMap = toPropertyMap(oldObjList, uniqueProperty);
                    final ImmutableMap<String, Object> newMap = toPropertyMap(newObjList, uniqueProperty);

                    parameterUnion.forEach(param -> builder
                            .addAll(createModifiedRows(oldMap.get(param), newMap.get(param), fieldIndent + 1)));
                }
            } else if (oldValue.isPresent() && newValue.isPresent() && oldValue.get().equals(newValue.get())) {
                //Element is the same in both contracts
                builder.add(new NoChangeRow(fieldIndent, property, oldValue.get()));
            } else {
                //Element is different between old and new contracts
                builder.add(new ModifiedRow(fieldIndent, property, oldValue.orElse(RowConstants.NA),
                        newValue.orElse(RowConstants.NA)));
            }
        }
    }
    return builder.build();
}

From source file:cop.raml.mocks.MockUtils.java

private static TypeElementMock createClassElement(@NotNull Class<?> cls) throws ClassNotFoundException {
    TypeElementMock element = new TypeElementMock(cls.getName(), ElementKind.CLASS);
    element.setType(new TypeMirrorMock(element, TypeMirrorMock.getTypeKind(cls)));

    if (cls.getName().startsWith("cop.") || cls.getName().startsWith("spring.")) {
        VariableElementMock var;

        for (Field field : cls.getDeclaredFields())
            if ((var = createVariable(field.getName(), field.getType(),
                    Modifier.isStatic(field.getModifiers()))) != null)
                element.addEnclosedElement(setAnnotations(var, field));

        ExecutableElementMock exe;//from   w w w .j  ava  2s .  co m

        for (Method method : cls.getDeclaredMethods())
            if ((exe = createExecutable(method)) != null)
                element.addEnclosedElement(setAnnotations(exe, method));
    }

    return setAnnotations(element, cls);
}

From source file:misc.TestUtils.java

public static List<Pair<String, Object>> getEntityFields(Object o) {
    List<Pair<String, Object>> ret = new ArrayList<Pair<String, Object>>();
    for (Class<?> clazz = o.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
        for (Field field : clazz.getDeclaredFields()) {
            //ignore some weird fields with unique values
            if (field.getName().contains("$"))
                continue;
            boolean accessible = field.isAccessible();
            try {
                field.setAccessible(true);
                Object val = field.get(o);
                ret.add(new Pair<String, Object>(field.getName(), val));
                //               System.out.println(field.getName()+"="+val);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();//from w ww .  j a  v a 2 s.co m
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } finally {
                field.setAccessible(accessible);
            }
        }
    }
    return ret;
}

From source file:com.netflix.astyanax.util.StringUtils.java

public static <T> String joinClassAttributeValues(final T object, String name, Class<T> clazz) {
    Field[] fields = clazz.getDeclaredFields();

    StringBuilder sb = new StringBuilder();
    sb.append(name).append("[");
    sb.append(org.apache.commons.lang.StringUtils.join(Collections2.transform(
            // Filter any field that does not start with lower case
            // (we expect constants to start with upper case)
            Collections2.filter(Arrays.asList(fields), new Predicate<Field>() {
                @Override/*  ww  w. j  ava 2s.  c o m*/
                public boolean apply(Field field) {
                    if ((field.getModifiers() & Modifier.STATIC) == Modifier.STATIC)
                        return false;
                    return Character.isLowerCase(field.getName().charAt(0));
                }
            }),
            // Convert field to "name=value". value=*** on error
            new Function<Field, String>() {
                @Override
                public String apply(Field field) {
                    Object value;
                    try {
                        value = field.get(object);
                    } catch (Exception e) {
                        value = "***";
                    }
                    return field.getName() + "=" + value;
                }
            }), ","));
    sb.append("]");

    return sb.toString();
}

From source file:Main.java

/**
 * Converts a color into a string. If the color is equal to one of the defined
 * constant colors, that name is returned instead. Otherwise the color is
 * returned as hex-string.//ww w.j a  v a2s. c  o m
 * 
 * @param c
 *          the color.
 * @return the string for this color.
 */
public static String colorToString(final Color c) {
    try {
        final Field[] fields = Color.class.getFields();
        for (int i = 0; i < fields.length; i++) {
            final Field f = fields[i];
            if (Modifier.isPublic(f.getModifiers()) && Modifier.isFinal(f.getModifiers())
                    && Modifier.isStatic(f.getModifiers())) {
                final String name = f.getName();
                final Object oColor = f.get(null);
                if (oColor instanceof Color) {
                    if (c.equals(oColor)) {
                        return name;
                    }
                }
            }
        }
    } catch (Exception e) {
        //
    }

    // no defined constant color, so this must be a user defined color
    final String color = Integer.toHexString(c.getRGB() & 0x00ffffff);
    final StringBuffer retval = new StringBuffer(7);
    retval.append("#");

    final int fillUp = 6 - color.length();
    for (int i = 0; i < fillUp; i++) {
        retval.append("0");
    }

    retval.append(color);
    return retval.toString();
}

From source file:in.mycp.utils.Commons.java

public static List getAllJbpmProcDefNames() {
    // public static final String JBPM_PROC_DEF_NAME_FVC_BILL = "fvc bill";
    Field[] allFields = Commons.class.getFields();
    List<String> fieldList = new ArrayList<String>();
    for (int i = 0; i < allFields.length; i++) {
        Field eachField = allFields[i];
        if (eachField.getName().startsWith("JBPM_PROC_DEF_NAME")) {
            try {
                fieldList.add((String) eachField.get(Commons.class));
            } catch (Exception e) {
            }// ww w.  j a  va  2 s  . c  om
        }
    }
    return fieldList;
}

From source file:com.Da_Technomancer.crossroads.API.packets.Message.java

private static Field[] getClassFields(Class<?> clazz) {
    if (fieldCache.containsValue(clazz))
        return fieldCache.get(clazz);
    else {/*from   w  ww. ja va2s.  c  o  m*/
        Field[] fields = clazz.getFields();
        Arrays.sort(fields, (Field f1, Field f2) -> {
            return f1.getName().compareTo(f2.getName());
        });
        fieldCache.put(clazz, fields);
        return fields;
    }
}

From source file:com.pinterest.deployservice.common.ChangeFeedJob.java

private static String toStringRepresentation(Object object) throws IllegalAccessException {
    if (object == null) {
        return "None";
    }//from  w w w.  j  a v  a 2s .  co  m

    if (object instanceof List) {
        List<?> list = (List<?>) object;
        if (list.isEmpty()) {
            return "[]";
        }

        StringBuilder sb = new StringBuilder("[");
        for (Object element : list) {
            sb.append(toStringRepresentation(element));
            sb.append(", ");
        }

        sb.delete(sb.length() - 2, sb.length());
        sb.append(']');
        return sb.toString();
    }

    Field[] fields = object.getClass().getDeclaredFields();
    if (fields.length == 0) {
        return "{}";
    }

    StringBuilder sb = new StringBuilder("{");
    for (Field field : fields) {
        field.setAccessible(true);
        Object fieldItem = field.get(object);
        sb.append(field.getName());
        sb.append(":");
        sb.append(fieldItem);
        sb.append(", ");
    }

    sb.delete(sb.length() - 2, sb.length());
    sb.append('}');
    return sb.toString();
}

From source file:com.searchbox.core.ref.ReflectionUtils.java

public static void inspectAndSaveAttribute(Class<?> searchElement, Collection<AttributeEntity> attributes) {
    if (searchElement != null) {
        for (Field field : searchElement.getDeclaredFields()) {
            if (field.isAnnotationPresent(SearchAttribute.class)) {
                AttributeEntity attrDef = new AttributeEntity().setName(field.getName())
                        .setType(field.getType());
                String value = field.getAnnotation(SearchAttribute.class).value();
                if (value != null && !value.isEmpty()) {
                    try {
                        Object ovalue = BeanUtils.instantiateClass(field.getType().getConstructor(String.class),
                                value);/*from   w  w  w .j a v  a2  s .c  o m*/
                        attrDef.setValue(ovalue);
                    } catch (BeanInstantiationException | NoSuchMethodException | SecurityException e) {
                        LOGGER.trace("Could not construct default value (not much of a problem)", e);
                    }
                }
                attributes.add(attrDef);
            }
        }
        inspectAndSaveAttribute(searchElement.getSuperclass(), attributes);
    } else {
        return;
    }
}