I know my answer comes little late. I created a view methods that can do exactly this:
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import lombok.NonNull;
public final class ReflectionExtensions
{
public static Field[] getAllDeclaredFields(final @NonNull Class<?> cls,
List<String> ignoreFieldNames)
{
Field[] declaredFields = getDeclaredFields(cls, ignoreFieldNames);
Class<?> superClass = cls.getSuperclass();
if (superClass != null && superClass.equals(Object.class))
{
return declaredFields;
}
List<Field> fields = new ArrayList<>(Arrays.asList(declaredFields));
while (superClass != null
&& !(superClass.getSuperclass() != null && superClass.equals(Object.class)))
{
fields.addAll(Arrays.asList(getDeclaredFields(superClass, ignoreFieldNames)));
superClass = superClass.getSuperclass();
}
return fields.toArray(newArrayInstance(Field.class, fields.size()));
}
public static Field[] getDeclaredFields(final @NonNull Class<?> cls,
List<String> ignoreFieldNames) throws SecurityException
{
Field[] declaredFields = cls.getDeclaredFields();
return Arrays.stream(declaredFields)
.filter(field -> !ignoreFieldNames.contains(field.getName())).toArray(Field[]::new);
}
public static <T> T[] newArrayInstance(final @NonNull Class<T> cls, final int length)
{
return (T[])Array.newInstance(cls, length);
}
public static String[] getDefaultIgnoreFieldNames()
{
return new String[] { "serialVersionUID", "$jacocoData" };
}
}
and a unit test for it:
import io.github.astrapi69.test.objects.Member;
import io.github.astrapi69.test.objects.Person;
import io.github.astrapi69.test.objects.PremiumMember;
import org.testng.annotations.Test;
import java.lang.reflect.Field;
import static org.testng.AssertJUnit.assertEquals;
public class ReflectionExtensionsTest
{
@Test
public void testGetAllDeclaredFields()
{
int expected;
int actual;
Field[] allDeclaredFields;
allDeclaredFields = io.github.astrapi69.reflection.ReflectionExtensions.getAllDeclaredFields(
Person.class,
io.github.astrapi69.reflection.ReflectionExtensions.getDefaultIgnoreFieldNames());
expected = 5;
actual = allDeclaredFields.length;
assertEquals(expected, actual);
allDeclaredFields = io.github.astrapi69.reflection.ReflectionExtensions.getAllDeclaredFields(
Member.class,
io.github.astrapi69.reflection.ReflectionExtensions.getDefaultIgnoreFieldNames());
expected = 7;
actual = allDeclaredFields.length;
assertEquals(expected, actual);
allDeclaredFields = io.github.astrapi69.reflection.ReflectionExtensions.getAllDeclaredFields(
PremiumMember.class,
ReflectionExtensions.getDefaultIgnoreFieldNames());
expected = 8;
actual = allDeclaredFields.length;
assertEquals(expected, actual);
}
}
The test classes are from test-object repository.