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:net.ceos.project.poi.annotated.annotation.XlsFreeElementTest.java

/**
 * Test initialization of the transformMask attribute with specific value.
 */// w  w  w.  j av  a 2 s.co m
@Test
public void checkTransformMaskAttribute() {
    Class<XMenFactory.ProfessorX> oC = XMenFactory.ProfessorX.class;

    List<Field> fL = Arrays.asList(oC.getDeclaredFields());
    for (Field f : fL) {
        // Process @XlsFreeElement
        if (f.isAnnotationPresent(XlsFreeElement.class)) {

            XlsFreeElement xlsFreeElement = (XlsFreeElement) f.getAnnotation(XlsFreeElement.class);

            if (f.getName().equals("doubleFreeAttribute")
                    && StringUtils.isNotBlank(xlsFreeElement.transformMask())) {
                assertEquals(xlsFreeElement.transformMask(), "0.00");
            }
        }
    }
}

From source file:CrossRef.java

/**
 * Print the fields and methods of one class.
 *///from w w w.  ja  v  a  2 s  .  c  o m
protected void doClass(Class c) {
    int i, mods;
    startClass(c);
    try {
        Field[] fields = c.getDeclaredFields();
        Arrays.sort(fields, new Comparator() {
            public int compare(Object o1, Object o2) {
                return ((Field) o1).getName().compareTo(((Field) o2).getName());
            }
        });
        for (i = 0; i < fields.length; i++) {
            Field field = (Field) fields[i];
            if (!Modifier.isPrivate(field.getModifiers()))
                putField(field, c);
            // else System.err.println("private field ignored: " + field);
        }

        Method methods[] = c.getDeclaredMethods();
        // Arrays.sort(methods);
        for (i = 0; i < methods.length; i++) {
            if (!Modifier.isPrivate(methods[i].getModifiers()))
                putMethod(methods[i], c);
            // else System.err.println("pvt: " + methods[i]);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    endClass();
}

From source file:ch.ifocusit.plantuml.classdiagram.ClassDiagramBuilder.java

public ClassAttribute[] readFields(Class aClass) {
    return Stream.of(aClass.getDeclaredFields())
            // exclude inner class
            .filter(field -> !field.getName().startsWith(DOLLAR))
            // exclude static fields
            .filter(field -> field.getDeclaringClass().isEnum() || !Modifier.isStatic(field.getModifiers()))
            .map(this::createClassAttribute)
            // excludes specific fields
            .filter(filterFields()).toArray(ClassAttribute[]::new);
}

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

@SuppressWarnings("unchecked")
private IRecordTable commonConstructor(final Class clazz) {
    if (clazz == null)
        return null;
    final IRecordTable t = (IRecordTable) clazz.getAnnotation(IRecordTable.class);
    for (Field field : clazz.getDeclaredFields()) {
        final IRecordField definition = field.getAnnotation(IRecordField.class);
        if (definition == null)
            continue;
        if (definition.unique())
            uniqueFieldName = field.getName();
        parameters.add(createParameter(field));
    }//from  ww  w .  j a  v  a2 s .c  om
    final IRecordTable tt = commonConstructor(clazz.getSuperclass());
    return (t == null) ? tt : t;
}

From source file:com.shazam.shazamcrest.CyclicReferenceDetector.java

/**
 * Detects classes that have circular reference.
 * //from  ww w .  j av  a 2 s .c  o m
 * @param object the object to check if it has circular reference fields
 * @param clazz the class being used (necessary if we also checking super class as getDeclaredFields only returns
 *              fields of a given class, but not its super class)
 */
private void detectCircularReferenceOnFields(Object object, Class<?> clazz) {
    if (objectsWithCircularReferences.contains(object)) {
        return;
    }

    for (Field field : clazz.getDeclaredFields()) {
        field.setAccessible(true);

        if (!isStatic(field.getModifiers())) {
            try {
                Object fieldValue = field.get(object);
                if (fieldValue != null) {
                    detectCircularReferenceOnObject(fieldValue);
                }
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }
    detectCircularReferencesFromTheSuperClass(object, clazz);
}

From source file:org.springmodules.cache.util.Reflections.java

/**
 * <p>/* w w  w.  j  ava  2 s . c  o m*/
 * This method uses reflection to build a valid hash code.
 * </p>
 *
 * <p>
 * It uses <code>AccessibleObject.setAccessible</code> to gain access to
 * private fields. This means that it will throw a security exception if run
 * under a security manager, if the permissions are not set up correctly. It
 * is also not as efficient as testing explicitly.
 * </p>
 *
 * <p>
 * Transient members will not be used, as they are likely derived fields,
 * and not part of the value of the <code>Object</code>.
 * </p>
 *
 * <p>
 * Static fields will not be tested. Superclass fields will be included.
 * </p>
 *
 * @param obj
 *          the object to create a <code>hashCode</code> for
 * @return the generated hash code, or zero if the given object is
 *         <code>null</code>
 */
public static int reflectionHashCode(Object obj) {
    if (obj == null)
        return 0;

    Class targetClass = obj.getClass();
    if (Objects.isArrayOfPrimitives(obj) || Objects.isPrimitiveOrWrapper(targetClass)) {
        return Objects.nullSafeHashCode(obj);
    }

    if (targetClass.isArray()) {
        return reflectionHashCode((Object[]) obj);
    }

    if (obj instanceof Collection) {
        return reflectionHashCode((Collection) obj);
    }

    if (obj instanceof Map) {
        return reflectionHashCode((Map) obj);
    }

    // determine whether the object's class declares hashCode() or has a
    // superClass other than java.lang.Object that declares hashCode()
    Class clazz = (obj instanceof Class) ? (Class) obj : obj.getClass();
    Method hashCodeMethod = ReflectionUtils.findMethod(clazz, "hashCode", new Class[0]);

    if (hashCodeMethod != null) {
        return obj.hashCode();
    }

    // could not find a hashCode other than the one declared by java.lang.Object
    int hash = INITIAL_HASH;

    try {
        while (targetClass != null) {
            Field[] fields = targetClass.getDeclaredFields();
            AccessibleObject.setAccessible(fields, true);

            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                int modifiers = field.getModifiers();

                if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers)) {
                    hash = MULTIPLIER * hash + reflectionHashCode(field.get(obj));
                }
            }
            targetClass = targetClass.getSuperclass();
        }
    } catch (IllegalAccessException exception) {
        // ///CLOVER:OFF
        ReflectionUtils.handleReflectionException(exception);
        // ///CLOVER:ON
    }

    return hash;
}

From source file:org.zols.datastore.validator.TV4.java

private String addIdField(Class type, Map<String, Object> jsonSchemaAsMap) throws JsonProcessingException {
    jsonSchemaAsMap.put("id", type.getName());
    for (Field field : type.getDeclaredFields()) {
        if (field.isAnnotationPresent(Id.class)) {
            jsonSchemaAsMap.put(ID_FIELD, field.getName());
        }/*from   w w  w .  j  a v a  2 s .co m*/
    }
    return mapper.writeValueAsString(jsonSchemaAsMap);
}

From source file:com.monits.jpack.codec.ObjectCodec.java

public ObjectCodec(Class<? extends E> struct) {

    this.struct = struct;

    fields = new ArrayList<FieldData>();
    for (Field field : struct.getDeclaredFields()) {
        Encode annotation = field.getAnnotation(Encode.class);
        if (annotation != null) {
            FieldData data = new FieldData();

            data.metadata = annotation;//from  ww  w.  j a  va 2 s .  co  m
            data.codec = (Codec<Object>) CodecFactory.get(field);

            if (data.codec == null) {
                continue;
            }

            data.field = field;
            data.field.setAccessible(true);

            fields.add(data);
        }
    }

    Collections.sort(fields, new Comparator<FieldData>() {

        @Override
        public int compare(FieldData a, FieldData b) {
            return a.metadata.value() - b.metadata.value();
        }

    });
}

From source file:com.ls.http.base.handler.MultipartRequestHandler.java

private void formMultipartEntityObject(Object source) {
    Class<?> currentClass = source.getClass();
    while (!Object.class.equals(currentClass)) {
        Field[] fields = currentClass.getDeclaredFields();
        for (int counter = 0; counter < fields.length; counter++) {
            Field field = fields[counter];
            Expose expose = field.getAnnotation(Expose.class);
            if (expose != null && !expose.deserialize() || Modifier.isTransient(field.getModifiers())) {
                continue;// We don't have to copy ignored fields.
            }/*from ww  w .j a v a2  s .c o  m*/
            field.setAccessible(true);
            Object value;

            String name;
            SerializedName serializableName = field.getAnnotation(SerializedName.class);
            if (serializableName != null) {
                name = serializableName.value();
            } else {
                name = field.getName();
            }
            try {
                value = field.get(source);
                addEntity(name, value);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        currentClass = currentClass.getSuperclass();
    }
    httpentity = entity.build();
}

From source file:net.ceos.project.poi.annotated.annotation.XlsElementTest.java

/**
 * Test default configuration./*from  ww w.j a  v a  2 s .  co  m*/
 */
@Test
public void checkDefaultConfiguration() {
    Class<XMenFactory.DefaultConfig> oC = XMenFactory.DefaultConfig.class;

    List<Field> fL = Arrays.asList(oC.getDeclaredFields());
    for (Field f : fL) {
        // Process @XlsElement
        if (f.isAnnotationPresent(XlsElement.class)) {

            XlsElement xlsElement = (XlsElement) f.getAnnotation(XlsElement.class);

            assertEquals(xlsElement.comment(), "");
            assertEquals(xlsElement.commentRules(), "");
            assertEquals(xlsElement.decorator(), "");
            assertEquals(xlsElement.formatMask(), "");
            assertEquals(xlsElement.transformMask(), "");
            assertEquals(xlsElement.isFormula(), false);
            assertEquals(xlsElement.formula(), "");
            assertEquals(xlsElement.customizedRules(), "");
            assertEquals(xlsElement.columnWidthInUnits(), 0);
            assertEquals(xlsElement.parentSheet(), false);
        }
    }
}