Java reflection get all private fields

JavaReflectionFieldPrivate

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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().

Solution 2 - Java

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;
	}
}

Solution 3 - Java

Try FieldUtils from apache commons-lang3:

FieldUtils.getAllFieldsList(Class<?> cls)

Solution 4 - Java

Using Java 8 :

Field[] fields = String.class.getDeclaredFields();
List<Field> privateFieldList = Arrays.asList(fields).stream().filter(field -> Modifier.isPrivate(field.getModifiers())).collect(
        Collectors.toList());

Solution 5 - Java

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));
     }
    

    }

Solution 6 - Java

Do you mean like

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2152361View Question on Stackoverflow
Solution 1 - JavaCyrille KaView Answer on Stackoverflow
Solution 2 - JavaKevin BowersoxView Answer on Stackoverflow
Solution 3 - JavaMartin SchröderView Answer on Stackoverflow
Solution 4 - JavaSahil ChhabraView Answer on Stackoverflow
Solution 5 - JavamadxView Answer on Stackoverflow
Solution 6 - JavaPeter LawreyView Answer on Stackoverflow