Understand Java Stream.Iterate() behavior with generic types

Viewed 81

I am new to Java generics and trying to understand how Stream.iterate() works with generic types. I have a validator class that has some validation and manipulation logic using reflection. In the validator class one version of the Stream.iterate works and other does not and i have no idea why it does not work. This the abstract class i have which calls the validate method in validator class.

public abstract class AbstractClass<T> {

  private void initialize() {
    validator.validate(this);
  }

}

And in the validator class I am trying to get the stream of fields for validation, but I am only able to get the stream of class, not stream of fields.

public class Validator{

 public void validate(final Object object){
  final Class<?> type = object.getClass();
  classSupplier(type).get()... // This works
  fieldsSupplier(type).get()... // But I want to make this work
 }

 private Supplier<Stream<Class<?>>> classSupplier(final Class<?> type) {
        return () -> Stream.iterate(type, Objects::nonNull, Class::getSuperclass);
 }

 private Supplier<Stream<Field>> fieldsSupplier(final Class<?> type) {
        return () -> Stream.iterate(type, Objects::nonNull, Class::getSuperclass) // "Bad return type in method reference: cannot convert java.lang.Class<? super ?> to java.lang.Class<?>"
                .flatMap(klass -> Stream.of(klass.getDeclaredFields()));
 }

}

The above code does not compile. I guess I am missing something important to even understand what is happening here. How do i achieve what i am trying and what i need to know to understand why this is not working.

0 Answers
Related