Java reflection obtener todos los campos privados


Me pregunto si hay una manera de obtener todos los campos privados de alguna clase en java y su tipo.

Por ejemplo supongamos que tengo una clase

class SomeClass {
    private String aaa;
    private SomeOtherClass bbb;
    private double ccc;
}

Ahora me gustaría obtener todos los campos privados(aaa, bbb, ccc) de clase SomeClass (Sin conocer el nombre de todos los campos por adelantado) y comprobar su tipo.

Author: jmattheis, 2013-03-10

6 answers

Es posible obtener todos los campos con el método getDeclaredFields() de Class. Luego hay que comprobar el modificador de cada campo para encontrar los privados:

List<Field> privateFields = new ArrayList<>();
Field[] allFields = SomeClass.class.getDeclaredFields();
for (Field field : allFields) {
    if (Modifier.isPrivate(field.getModifiers())) {
        privateFields.add(field);
    }
}

Tenga en cuenta que getDeclaredFields() no devolverá los campos heredados.

Finalmente, se obtiene el tipo de los campos con el campo method .GetType () .

 104
Author: Cyrille Ka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-03 09:08:57

Puede usar Modifier para determinar si un campo es privado. Asegúrese de usar el método getDeclaredFields para asegurarse de recuperar campos privados de la clase, llamando a getFields solo devolverá los campos públicos.

public class SomeClass {

    private String aaa;
    private Date date;
    private double ccc;
    public int notPrivate;

    public static void main(String[] args) {
        List<Field> fields = getPrivateFields(SomeClass.class);
        for(Field field: fields){
            System.out.println(field.getName());
        }
    }

    public static List<Field> getPrivateFields(Class<?> theClass){
        List<Field> privateFields = new ArrayList<Field>();

        Field[] fields = theClass.getDeclaredFields();

        for(Field field:fields){
            if(Modifier.isPrivate(field.getModifiers())){
                privateFields.add(field);
            }
        }
        return privateFields;
    }
}
 12
Author: Kevin Bowersox,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-05 21:08:46

Intente FieldUtils de apache commons-lang3:

FieldUtils.getAllFieldsList(Class<?> cls)
 6
Author: Martin Schröder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-25 09:22:31

Compruebe si un campo es privado

Puedes filtrar los campos usando el modificador .isPrivate :

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
// ...
Field field = null;
// retrieve the field in some way
// ...
Modifier.isPrivate(field.getModifiers())

En un único objeto Field que devuelve true si el campo es private


Reúne todos los campos de una clase

Para recoger todos los Campos use:

1) Si solo necesita los campos de la clase sin los campos tomados de la jerarquía de clases, simplemente podría usar:

Field[] fields = SomeClass.class.getDeclaredFields();

2) Si no quieres reinvente la rueda y obtenga todos los campos de una jerarquía de clases en la que podría confiar Apache Commons Lang versión 3.2 + que proporciona FieldUtils.getAllFieldsList:

import java.lang.reflect.Field;
import java.util.AbstractCollection;
import java.util.AbstractList;
import java.util.AbstractSequentialList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang3.reflect.FieldUtils;
import org.junit.Assert;
import org.junit.Test;

public class FieldUtilsTest {

    @Test
    public void testGetAllFieldsList() {

        // Get all fields in this class and all of its parents
        final List<Field> allFields = FieldUtils.getAllFieldsList(LinkedList.class);

        // Get the fields form each individual class in the type's hierarchy
        final List<Field> allFieldsClass = Arrays.asList(LinkedList.class.getFields());
        final List<Field> allFieldsParent = Arrays.asList(AbstractSequentialList.class.getFields());
        final List<Field> allFieldsParentsParent = Arrays.asList(AbstractList.class.getFields());
        final List<Field> allFieldsParentsParentsParent = Arrays.asList(AbstractCollection.class.getFields());

        // Test that `getAllFieldsList` did truly get all of the fields of the the class and all its parents 
        Assert.assertTrue(allFields.containsAll(allFieldsClass));
        Assert.assertTrue(allFields.containsAll(allFieldsParent));
        Assert.assertTrue(allFields.containsAll(allFieldsParentsParent));
        Assert.assertTrue(allFields.containsAll(allFieldsParentsParentsParent));
    }
}
 6
Author: madx,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-12 09:38:35

Usando Java 8:

Field[] fields = String.class.getDeclaredFields();
List<Field> privateFieldList = Arrays.asList(fields).stream().filter(field -> Modifier.isPrivate(field.getModifiers())).collect(
        Collectors.toList());
 6
Author: Sahil Chhabra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-26 08:43:02

¿quieres decir como

Field[] fields = SomeClass.class.getDeclaredFields();
 4
Author: Peter Lawrey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-09 20:14:13