Java reflection get all private fields

后端 未结 6 782
北恋
北恋 2020-12-07 22:29

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 {
            


        
6条回答
  •  隐瞒了意图╮
    2020-12-07 23:08

    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 allFields = FieldUtils.getAllFieldsList(LinkedList.class);
    
            // Get the fields form each individual class in the type's hierarchy
            final List allFieldsClass = Arrays.asList(LinkedList.class.getFields());
            final List allFieldsParent = Arrays.asList(AbstractSequentialList.class.getFields());
            final List allFieldsParentsParent = Arrays.asList(AbstractList.class.getFields());
            final List 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));
        }
    }
    

提交回复
热议问题