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.expedia.seiso.domain.meta.DynaItem.java

public DynaItem(@NonNull Item item) {
    this.item = item;
    this.itemClass = item.getClass();

    String metaKeyFieldName = null;

    // Use currClass to search up the inheritance hierarchy. We need this for example to find the @Key for Vip
    // subclasses, since the @Key is defined in Vip.
    Class<?> currClass = itemClass;
    do {//from  w  w w.jav a 2s. co  m
        val fields = currClass.getDeclaredFields();
        for (val field : fields) {
            val anns = field.getAnnotations();
            for (val ann : anns) {
                if (ann.annotationType() == Key.class) {
                    metaKeyFieldName = field.getName();
                }
            }
        }
    } while (metaKeyFieldName == null && (currClass = currClass.getSuperclass()) != null);

    // FIXME This doesn't handle compound keys. Use the ItemKey instead! [WLW]
    // If there's no explicit @Key, then use the ID by default.
    if (metaKeyFieldName == null) {
        metaKeyFieldName = "id";
    }

    this.metaKeyProperty = BeanUtils.getPropertyDescriptor(itemClass, metaKeyFieldName);
    val metaKeyGetter = metaKeyProperty.getReadMethod();

    try {
        this.metaKey = (Serializable) metaKeyGetter.invoke(item);
    } catch (IllegalAccessException | InvocationTargetException e) {
        throw new RuntimeException(e);
    }

    // log.trace("Using key {}={} for itemClass={}", metaKeyFieldName, metaKey, itemClass.getSimpleName());
}

From source file:com.sdl.odata.datasource.jpa.ODataProxyProcessor.java

private void unproxyElements(Object entity, Set<Object> visitedEntities, List<String> expandProperties)
        throws ODataDataSourceException {
    if (visitedEntities.contains(entity)) {
        return;/*from  w  w  w .j  ava  2s  .c o m*/
    }
    //put entity to set of already visited
    visitedEntities.add(entity);
    Class reflectObj = entity.getClass();
    Field[] fields = reflectObj.getDeclaredFields();
    boolean sourceEntity = visitedEntities.size() == 1;

    for (Field field : fields) {
        field.setAccessible(true);
        try {
            Object fieldType = field.get(entity);
            if (isJPAEntity(fieldType)) {
                unproxyElements(fieldType, visitedEntities, expandProperties);
            } else if (fieldType instanceof PersistentCollection) {
                PersistentCollection collection = (PersistentCollection) fieldType;
                if (collection.wasInitialized()) {
                    for (Object element : (Iterable<?>) collection) {
                        unproxyElements(element, visitedEntities, expandProperties);
                    }
                } else {
                    if (!sourceEntity && !isEntityExpanded(entity, expandProperties)) {
                        if (fieldType instanceof List) {
                            // Hibernate checks if the current field type is a hibernate proxy
                            LOG.debug("This collection is lazy initialized. Replaced by an empty list.");
                            field.set(entity, new ArrayList<>());
                        } else if (fieldType instanceof Set) {
                            LOG.debug("This set is lazy initialized. Replaced by an empty set.");
                            field.set(entity, new HashSet<>());
                        }
                    } else {
                        // These properties will be loaded during mapping
                        field.set(entity, null);
                    }
                }
            }
        } catch (IllegalAccessException e) {
            throw new ODataDataSourceException("Cannot un-proxy elements of: " + reflectObj.getName(), e);
        }
    }
}

From source file:de.hska.ld.content.dto.DocumentListItemDto.java

public DocumentListItemDto(Document document) {
    try {/*from  www  . jav a  2 s .  c o m*/
        // extract and set values per reflection
        Class subclass = document.getClass();
        Class superclass = subclass.getSuperclass();
        while (superclass != null) {
            Field[] declaredFields = superclass.getDeclaredFields();
            for (Field documentfield : declaredFields) {
                documentfield.setAccessible(true);
                Object obj = documentfield.get(document);
                documentfield.set(this, obj);
            }
            superclass = superclass.getSuperclass();
        }
        Field[] declaredFields = document.getClass().getDeclaredFields();
        for (Field documentfield : declaredFields) {
            documentfield.setAccessible(true);
            Object obj = documentfield.get(document);
            documentfield.set(this, obj);
        }
        this.setId(document.getId());
    } catch (IllegalAccessException e) {
        //
    }
}

From source file:com.nabla.wapp.server.database.SqlInsert.java

protected void buildParameterList(final Class clazz) {
    if (clazz != null) {
        for (Field field : clazz.getDeclaredFields()) {
            final IRecordField definition = field.getAnnotation(IRecordField.class);
            if (definition != null)
                parameters.add(SqlStatement.createParameter(field));
        }//  ww  w. j a  v  a  2s . com
        buildParameterList(clazz.getSuperclass());
    }
}

From source file:com.microsoft.rest.serializer.FlatteningDeserializer.java

@SuppressWarnings("unchecked")
@Override/*w ww .  ja  va2 s. c o m*/
public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonNode root = mapper.readTree(jp);
    final Class<?> tClass = this.defaultDeserializer.handledType();
    for (Field field : tClass.getDeclaredFields()) {
        JsonNode node = root;
        JsonProperty property = field.getAnnotation(JsonProperty.class);
        if (property != null) {
            String value = property.value();
            if (value.matches(".+[^\\\\]\\..+")) {
                String[] values = value.split("((?<!\\\\))\\.");
                for (String val : values) {
                    val = val.replace("\\.", ".");
                    node = node.get(val);
                    if (node == null) {
                        break;
                    }
                }
                ((ObjectNode) root).put(value, node);
            }
        }
    }
    JsonParser parser = new JsonFactory().createParser(root.toString());
    parser.nextToken();
    return defaultDeserializer.deserialize(parser, ctxt);
}

From source file:org.vaadin.spring.i18n.Translator.java

private void analyzeFields(Class<?> clazz) {
    for (Field f : clazz.getDeclaredFields()) {
        if (f.isAnnotationPresent(TranslatedProperty.class)) {
            translatedFields.put(f.getAnnotation(TranslatedProperty.class), f);
        } else if (f.isAnnotationPresent(TranslatedProperties.class)) {
            for (TranslatedProperty annotation : f.getAnnotation(TranslatedProperties.class).value()) {
                translatedFields.put(annotation, f);
            }//from w ww.j  a  v  a  2 s . c o  m
        }
    }
}

From source file:com.hc.wx.server.common.bytecode.ReflectUtils.java

public static Map<String, Field> getBeanPropertyFields(Class cl) {
    Map<String, Field> properties = new HashMap<String, Field>();
    for (; cl != null; cl = cl.getSuperclass()) {
        Field[] fields = cl.getDeclaredFields();
        for (Field field : fields) {
            if (Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) {
                continue;
            }/*from ww w.  j  a va  2s .c  o m*/

            field.setAccessible(true);

            properties.put(field.getName(), field);
        }
    }

    return properties;
}

From source file:com.jaspersoft.jasperserver.api.metadata.olap.service.impl.OlapConnectionServiceImpl.java

/**
 * Searches all members of a Class until a member of the given type
 * is found.//  ww  w  . ja v  a2  s  .c  o m
 *
 *  Returns a reference to that Field or NULL if none found
 *
 *  WARNING:  this method will return the FIRST found member of the specified
 *            type.  Be sure that this is what you want.
 *            IF there are multiple members of type 'A', you will get the first one.
 *
 *
 * @param cl
 * @param typeName
 * @return
 */
public static Field getFieldByTypeName(Class cl, String typeName) {
    // Check we have valid arguments
    assert (cl != null);
    assert (typeName != null);

    final Field fields[] = cl.getDeclaredFields();
    for (int i = 0; i < fields.length; ++i) {
        if (typeName.equals(fields[i].getType().getName())) {

            fields[i].setAccessible(true);
            return fields[i];
        }
    }
    return null;
}

From source file:com.pamarin.income.lazyload.LazyLoad.java

private Object getIdOfInstance(Object instance) {
    Object instanceId = null;/*  w w  w  . j  av a 2 s  .c  o  m*/
    try {
        Class instanceClass = instance.getClass();
        Field[] fields = instanceClass.getDeclaredFields();
        Field idField = null;
        for (Field field : fields) {
            if (field.isAnnotationPresent(Id.class)) {
                idField = field;
                break;
            }
        }

        if (idField != null) {
            String idName = idField.getName();
            idName = idName.substring(0, 1).toUpperCase() + idName.substring(1);
            Method method = instanceClass.getDeclaredMethod("get" + idName);
            instanceId = method.invoke(instance);
        }
    } catch (Exception ex) {
        LOG.warn(null, ex);
    }

    return instanceId;
}

From source file:de.hska.ld.content.dto.FolderDto.java

public FolderDto(Folder folder) {
    try {/*from w w  w  .ja v a 2 s . c o  m*/
        Class subclass = folder.getClass();
        Class superclass = subclass.getSuperclass();
        while (superclass != null) {
            Field[] declaredFields = superclass.getDeclaredFields();
            for (Field folderfield : declaredFields) {
                folderfield.setAccessible(true);
                Object obj = folderfield.get(folder);
                folderfield.set(this, obj);
            }
            superclass = superclass.getSuperclass();
        }
        // extract and set values per reflection
        for (Field folderfield : folder.getClass().getDeclaredFields()) {
            folderfield.setAccessible(true);
            Object obj = folderfield.get(folder);
            folderfield.set(this, obj);
        }
        this.setId(folder.getId());
    } catch (IllegalAccessException e) {
        //
    }
    this.getJsonParentId();
}