Well, there is a way, but it needs takeWhile
that it is in jdk-9.
I'm doing a mapping here to get the names of the fields. You would have to add a @SuppressWarnings("null")
to the method.
System.out.println(Stream.iterate(this.getClass(), (Class<?> x) -> x.getSuperclass())
.takeWhile(x -> x != null)
.flatMap(c -> Arrays.stream(c.getDeclaredFields()))
.map(c -> c.getName())
.collect(Collectors.toList()));
jdk-9 also introduces a Stream.iterate
that acts like an Iterator with seed, hasNext, next
that is far more suited for your case.
You could use StreamEx library for this btw:
StreamEx.of(Stream.iterate(this.getClass(), (Class<?> x) -> x.getSuperclass()))
.takeWhile(x -> x != null)
.flatMap(c -> Arrays.stream(c.getDeclaredFields()))
.map(c -> c.getName())
.collect(Collectors.toList());
And with new iterate method:
Stream.iterate(this.getClass(), c -> c != null, (Class<?> c) -> c.getSuperclass())
.flatMap(c -> Arrays.stream(c.getDeclaredFields()))
.map(c -> c.getName())
.collect(Collectors.toList())