86

I wonder is there a way to get all private fields of some class in Java and their type.

For example lets suppose I have a class:

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

Now I would like to get all private fields (aaa, bbb, ccc) of class SomeClass (Without knowing name of all fields upfront) and check their type.

Lii
  • 11,553
  • 8
  • 64
  • 88
user2152361
  • 863
  • 1
  • 6
  • 4
  • 8
    @atk Nobody's forcing you to answer; but for many of us landing on this question from Google, the top answer is a far more succinct explanation than reading through long posts on reflection. Even the long-tail of questions like this contribute to what SO is today. – Angad Sep 03 '15 at 08:07
  • See [How do I read a private field in Java?](http://stackoverflow.com/q/1196192) – Martin Schröder Sep 25 '15 at 09:23

6 Answers6

135

It is possible to obtain all fields with the method getDeclaredFields() of Class. Then you have to check the modifier of each fields to find the private ones:

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

Note that getDeclaredFields() will not return inherited fields.

Eventually, you get the type of the fields with the method Field.getType().

jmattheis
  • 10,494
  • 11
  • 46
  • 58
Cyrille Ka
  • 15,328
  • 5
  • 38
  • 58
  • I think the fact that I'm working against a compiled class makes it quite inconvenient because the returned fields have names such as `m0`, `m1`, etc., and are of type `java.lang.reflect.Method`. This could be due to me trying to use reflection on a Spring Bean casted to an interface? – payne Dec 10 '20 at 19:41
13

You can use Modifier to determine if a field is private. Be sure to use the getDeclaredFields method to ensure that you retrieve private fields from the class, calling getFields will only return the public fields.

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;
    }
}
Community
  • 1
  • 1
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • 2
    @AfzaalAhmadZeeshan why did you change my edit "clazz" to "class", when we clearly need to use the variable "clazz" and not the keyword "class" – vallentin Nov 17 '13 at 19:05
  • I am sorry for that mistake, I thought this was a mistake as there was no variable assosiated with the document or the code anywhere! Pardon me for that.. – Afzaal Ahmad Zeeshan Nov 17 '13 at 19:25
  • 3
    @AfzaalAhmadZeeshan there was a variable, it is in the arguments of the method. Though, do you care to revoke your change, since I can't change it. – vallentin Nov 18 '13 at 03:47
11

Try FieldUtils from apache commons-lang3:

FieldUtils.getAllFieldsList(Class<?> cls)
Martin Schröder
  • 4,176
  • 7
  • 47
  • 81
9

Check if a Field is private

You could filter the Fields using Modifier.isPrivate:

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

on a single Field object which returns true if the field is private


Collect all Fields of a class

To collect the all the Fields use:

1) If you need only the fields of the the class without the fields taken from the class hierarchy you could simply use:

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

2) If you don't want to reinvent the wheel and get all the fields of a class hierarchy you could rely upon Apache Commons Lang version 3.2+ which provides 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));
    }
}
madx
  • 6,723
  • 4
  • 55
  • 59
7

Using Java 8 :

Field[] fields = String.class.getDeclaredFields();
List<Field> privateFieldList = Arrays.asList(fields).stream().filter(field -> Modifier.isPrivate(field.getModifiers())).collect(
        Collectors.toList());
Sahil Chhabra
  • 10,621
  • 4
  • 63
  • 62
5

Do you mean like

Field[] fields = SomeClass.class.getDeclaredFields();
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130