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.browseengine.bobo.serialize.JSONSerializer.java

public static JSONObject serializeJSONObject(JSONSerializable obj)
        throws JSONSerializationException, JSONException {
    if (obj instanceof JSONExternalizable) {
        return ((JSONExternalizable) obj).toJSON();
    }/*from  w w  w  .  j a v a  2s  . c o  m*/

    JSONObject jsonObj = new JSONObject();
    Class clz = obj.getClass();
    Field[] fields = clz.getDeclaredFields();

    for (int i = 0; i < fields.length; ++i) {
        fields[i].setAccessible(true);
        int modifiers = fields[i].getModifiers();
        if (!Modifier.isTransient(modifiers) && !Modifier.isStatic(modifiers)) {
            String name = fields[i].getName();
            Class type = fields[i].getType();

            try {
                Object value = fields[i].get(obj);

                if (type.isArray() && value != null) {
                    int len = Array.getLength(value);

                    Class cls = type.getComponentType();

                    JSONArray array = new JSONArray();

                    for (int k = 0; k < len; ++k) {
                        dumpObject(array, cls, value, k);
                    }
                    jsonObj.put(name, array);
                } else {
                    dumpObject(jsonObj, fields[i], obj);
                }
            } catch (Exception e) {
                throw new JSONSerializationException(e.getMessage(), e);
            }
        }
    }

    return jsonObj;
}

From source file:ClassTree.java

/**
 * Returns a description of the fields of a class.
 * @param the class to be described/*from  ww  w .  j  a va 2 s.c om*/
 * @return a string containing all field types and names
 */
public static String getFieldDescription(Class<?> c) {
    // use reflection to find types and names of fields
    StringBuilder r = new StringBuilder();
    Field[] fields = c.getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
        Field f = fields[i];
        if ((f.getModifiers() & Modifier.STATIC) != 0)
            r.append("static ");
        r.append(f.getType().getName());
        r.append(" ");
        r.append(f.getName());
        r.append("\n");
    }
    return r.toString();
}

From source file:com.diversityarrays.dal.db.DalDatabaseUtil.java

static public Map<Field, Column> buildEntityFieldColumnMap(Class<? extends DalEntity> entityClass) {
    Map<Field, Column> columnByField = new LinkedHashMap<Field, Column>();

    for (Field fld : entityClass.getDeclaredFields()) {
        if (!Modifier.isStatic(fld.getModifiers())) {
            Column column = fld.getAnnotation(Column.class);
            fld.setAccessible(true);/*w  w w .j  a v a2  s.c  o m*/
            columnByField.put(fld, column);
        }
    }

    return columnByField;
}

From source file:gumga.framework.application.GumgaUntypedRepository.java

public static List<Field> getTodosAtributos(Class classe) throws SecurityException {
    List<Field> aRetornar = new ArrayList<>();
    if (!classe.getSuperclass().equals(Object.class)) {
        aRetornar.addAll(getTodosAtributos(classe.getSuperclass()));
    }// w  ww. java2 s  .c  om
    aRetornar.addAll(Arrays.asList(classe.getDeclaredFields()));
    return aRetornar;
}

From source file:Main.java

public static Collection<Field> getDeepDeclaredFields(Class<?> c) {
    if (_reflectedFields.containsKey(c)) {
        return _reflectedFields.get(c);
    }/*  w  w w .j a v a  2 s . c  o  m*/
    Collection<Field> fields = new ArrayList<Field>();
    Class<?> curr = c;

    while (curr != null) {
        try {
            Field[] local = curr.getDeclaredFields();

            for (Field field : local) {
                if (!field.isAccessible()) {
                    try {
                        field.setAccessible(true);
                    } catch (Exception ignored) {
                    }
                }

                int modifiers = field.getModifiers();
                if (!Modifier.isStatic(modifiers) && !field.getName().startsWith("this$")
                        && !Modifier.isTransient(modifiers)) {
                    fields.add(field);
                }
            }
        } catch (ThreadDeath t) {
            throw t;
        } catch (Throwable ignored) {
        }

        curr = curr.getSuperclass();
    }
    _reflectedFields.put(c, fields);
    return fields;
}

From source file:be.fedict.commons.eid.consumer.tlv.TlvParser.java

private static <T> T parseThrowing(final byte[] file, final Class<T> tlvClass) throws InstantiationException,
        IllegalAccessException, DataConvertorException, UnsupportedEncodingException {
    final Field[] fields = tlvClass.getDeclaredFields();
    final Map<Integer, Field> tlvFields = new HashMap<Integer, Field>();
    final T tlvObject = tlvClass.newInstance();
    for (Field field : fields) {
        final TlvField tlvFieldAnnotation = field.getAnnotation(TlvField.class);
        if (null != tlvFieldAnnotation) {
            final int tagId = tlvFieldAnnotation.value();
            if (tlvFields.containsKey(new Integer(tagId))) {
                throw new IllegalArgumentException("TLV field duplicate: " + tagId);
            }/*from  w w  w. jav  a  2  s.com*/
            tlvFields.put(new Integer(tagId), field);
        }
        final OriginalData originalDataAnnotation = field.getAnnotation(OriginalData.class);
        if (null != originalDataAnnotation) {
            field.setAccessible(true);
            field.set(tlvObject, file);
        }
    }

    int idx = 0;
    while (idx < file.length - 1) {
        final byte tag = file[idx];
        idx++;
        byte lengthByte = file[idx];
        int length = lengthByte & 0x7f;
        while ((lengthByte & 0x80) == 0x80) {
            idx++;
            lengthByte = file[idx];
            length = (length << 7) + (lengthByte & 0x7f);
        }
        idx++;
        if (0 == tag) {
            idx += length;
            continue;
        }
        if (tlvFields.containsKey(new Integer(tag))) {
            final Field tlvField = tlvFields.get(new Integer(tag));
            final Class<?> tlvType = tlvField.getType();
            final ConvertData convertDataAnnotation = tlvField.getAnnotation(ConvertData.class);
            final byte[] tlvValue = copy(file, idx, length);
            Object fieldValue;
            if (null != convertDataAnnotation) {
                final Class<? extends DataConvertor<?>> dataConvertorClass = convertDataAnnotation.value();
                final DataConvertor<?> dataConvertor = dataConvertorClass.newInstance();
                fieldValue = dataConvertor.convert(tlvValue);
            } else if (String.class == tlvType) {
                fieldValue = new String(tlvValue, "UTF-8");
            } else if (Boolean.TYPE == tlvType) {
                fieldValue = true;
            } else if (tlvType.isArray() && Byte.TYPE == tlvType.getComponentType()) {
                fieldValue = tlvValue;
            } else {
                throw new IllegalArgumentException("unsupported field type: " + tlvType.getName());
            }
            if (null != tlvField.get(tlvObject) && false == tlvField.getType().isPrimitive()) {
                throw new RuntimeException("field was already set: " + tlvField.getName());
            }
            tlvField.setAccessible(true);
            tlvField.set(tlvObject, fieldValue);
        } else {
            LOG.debug("unknown tag: " + (tag & 0xff) + ", length: " + length);
        }
        idx += length;
    }
    return tlvObject;
}

From source file:com.github.juanmf.java2plant.Parser.java

protected static void addAggregations(Set<Relation> relations, Class<?> fromType) {
    Field[] declaredFields = fromType.getDeclaredFields();
    for (Field f : declaredFields) {
        addAggregation(relations, fromType, f);
    }//  w ww .ja  v a 2  s .  com
}

From source file:com.feilong.commons.core.lang.reflect.FieldUtil.java

/**
 *  Field ?? Class?,../*w ww .j a  va 2 s .  c om*/
 * 
 * <pre>
 * public,protected,,private
 * ?.
 * 
 * ??.
 * ?? Class ? void 0 .
 * </pre>
 * 
 * @param clz
 *            the clz
 * @return public,protected,,private?.
 * @see java.lang.Class#getDeclaredFields()
 * @see #getFieldsNames(Field[])
 */
public static String[] getDeclaredFieldNames(Class<?> clz) {
    Field[] declaredFields = clz.getDeclaredFields();
    return getFieldsNames(declaredFields);
}

From source file:net.cpollet.jixture.hibernate3.helper.Hibernate3MappingDefinitionHolder.java

private static Iterable<Field> getFieldsUpToObject(Class<?> startClass) {
    List<Field> currentClassFields = new ArrayList<Field>();
    currentClassFields.addAll(Arrays.asList(startClass.getDeclaredFields()));
    Class<?> parentClass = startClass.getSuperclass();

    if (null != parentClass) {
        List<Field> parentClassFields = (List<Field>) getFieldsUpToObject(parentClass);
        currentClassFields.addAll(parentClassFields);
    }//from  ww w  .  jav a  2  s . co  m

    return currentClassFields;
}

From source file:org.lambdamatic.internal.elasticsearch.codec.DocumentCodec.java

/**
 * Analyze the given domain type and returns the name of its field to use as the document id, if
 * available.//w w w.java  2  s  .  c o  m
 * 
 * @param domainType the domain type to analyze
 * @return the <strong>single</strong> Java field annotated with {@link DocumentIdField}. If no field
 *         matches the criteria or more than one field is matches these criteria, a
 *         {@link MappingException} is thrown.
 */
public static Field getIdField(final Class<?> domainType) {
    final List<Pair<Field, DocumentIdField>> candidateFields = Stream.of(domainType.getDeclaredFields())
            .map(field -> new Pair<>(field, field.getAnnotation(DocumentIdField.class)))
            .filter(pair -> pair.getRight() != null).collect(Collectors.toList());
    if (candidateFields.isEmpty()) {
        throw new MappingException("No field is annotated with @{} in type {}", DocumentIdField.class.getName(),
                domainType);
    } else if (candidateFields.size() > 1) {
        final String fieldNames = candidateFields.stream().map(pair -> pair.getLeft().getName())
                .collect(Collectors.joining(", "));
        throw new MappingException("More than one field is annotated with @{} in type {}: {}",
                DocumentIdField.class.getName(), domainType, fieldNames);
    }
    return candidateFields.get(0).getLeft();
}