这是与问题中提供的相同代码,但使用Spliterator
. 我希望有人能想出一个更简单、更聪明的答案。
Class<?> clazz;
Object value;
value = ...;
<Class<?>>walkLinks(value.getClass(), Class::getSuperclass).
...
public static <T> Stream<T> walkLinks(T start, Function<T, T> next)
{
WalkLinks<T> walker;
Stream<T> result;
walker = new WalkLinks<>(start, next);
result = StreamSupport.stream(walker, false);
return(result);
}
private static class WalkLinks<T> extends Spliterators.AbstractSpliterator<T>
{
private final Function<T, T> m_next;
private T m_value;
public WalkLinks(T value, Function<T, T> next)
{
super(Long.MAX_VALUE, Spliterator.ORDERED + Spliterator.NONNULL);
m_value = value;
m_next = next;
}
@Override
public boolean tryAdvance(Consumer<? super T> action)
{
if (m_value == null)
return(false);
action.accept(m_value);
m_value = m_next.apply(m_value);
return(true);
}
}