2

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.

Naman
  • 27,789
  • 26
  • 218
  • 353
thiru
  • 23
  • 2
  • 1
    Does this answer your question? [Generic type inference not working with method chaining?](https://stackoverflow.com/questions/24794924/generic-type-inference-not-working-with-method-chaining) – jrook Mar 07 '20 at 20:45
  • Possible solutions : 1) Separate chained method into another expression 2) add a generic parameter to the function signature like `>` 3) use a loop to traverse object graph. – jrook Mar 07 '20 at 20:47

0 Answers0