This getAllFields implementation is horribly inefficient, creating multiple ArrayList instances and arrays, repeatedly copying the entire data between them back and forth. Thankfully, class hierarchies rarely are that deep that this becomes a bottleneck.
Still, you can implement this with a straight-forward loop, which is simpler and more efficient:
public static Field[] getAllFields(Class<?> klass) {
List<Field> fields = new ArrayList<>();
for(; klass!=null; klass=klass.getSuperclass())
Collections.addAll(fields, klass.getDeclaredFields());
return fields.toArray(new Field[0]);
}
There is not the slightest benefit from using recursion here.
With a loop, you can easily create a Function if you really wish:
public void init(){
Function<Class<?>,Field[]> f = klass -> {
List<Field> fields = new ArrayList<>();
for(; klass!=null; klass=klass.getSuperclass())
Collections.addAll(fields, klass.getDeclaredFields());
return fields.toArray(new Field[0]);
};
Field[] someFields = f.apply(SomeClass.class);
}
Though, of course, there isn’t even a reason to put the loop into a Function at all. You only wanted to have a function here due to your wish to use that inefficient recursive implementation, but lambda expressions don’t support accessing themself at all. They only can access the field to which the instance implementing the functional interface got stored, if it was stored in a field, which you don’t want. With a local lambda expression, recursion is impossible.
With the straight-forward loop, you can just write
public void init(){
List<Field> fields = new ArrayList<>();
for(Class<?> klass=SomeClass.class; klass!=null; klass=klass.getSuperclass())
Collections.addAll(fields, klass.getDeclaredFields());
Field[] someFields = fields.toArray(new Field[0]);
}
though, actually, there is rarely a real reason for copying the contents of fields into an array, you could just work with the List<Field> instead.
That said, encapsulating the loop into a named method describing its purpose, like getAllFields, is actually a good thing. If you don’t want to expose it, declare it private instead of public.
Function<Class<?>, Field[]> f = MyClass::getAllFields;