Skip to content

Commit

Permalink
fix: Make findAncestor return Object for backward compatibility (#14242)
Browse files Browse the repository at this point in the history
  • Loading branch information
mshabarov committed Aug 2, 2022
1 parent 0afd496 commit e084d39
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 22 deletions.
31 changes: 15 additions & 16 deletions flow-server/src/main/java/com/vaadin/flow/component/Component.java
Expand Up @@ -702,28 +702,27 @@ public void scrollIntoView() {
}

/**
* Traverses the component tree up and returns the first component that
* matches the given type.
* Traverses the component tree up and returns the first ancestor component
* that matches the given type.
*
* @param componentType
* the class of the component to search for
* @return the component as Optional or empty Optional if a parent of given
* type is not found
* the class of the ancestor component to search for
* @return The first ancestor that can be assigned to the given class. Null
* if no ancestor with the correct type could be found.
* @param <T>
* the type of the component to return
*/
@SuppressWarnings("unchecked")
public <T> Optional<T> findAncestor(Class<T> componentType) {
Optional<Component> parent = getParent();
while (parent.isPresent()) {
Component component = parent.get();
if (componentType.isAssignableFrom(component.getClass())) {
return Optional.of((T) component);
* the type of the ancestor component to return
*/
public <T> T findAncestor(Class<T> componentType) {
Optional<Component> optionalParent = getParent();
while (optionalParent.isPresent()) {
Component parent = optionalParent.get();
if (componentType.isAssignableFrom(parent.getClass())) {
return componentType.cast(parent);
} else {
parent = component.getParent();
optionalParent = parent.getParent();
}
}
return Optional.empty();
return null;
}

}
Expand Up @@ -1672,12 +1672,10 @@ public void findAncestorTest() {
ui.add(componentContainer);

Assert.assertEquals(componentContainer,
component.findAncestor(TestComponentContainer.class).get());
Assert.assertEquals(ui, component.findAncestor(UI.class).get());
Assert.assertEquals(ui,
component.findAncestor(PollNotifier.class).get());
Assert.assertFalse(
component.findAncestor(TestButton.class).isPresent());
component.findAncestor(TestComponentContainer.class));
Assert.assertEquals(ui, component.findAncestor(UI.class));
Assert.assertEquals(ui, component.findAncestor(PollNotifier.class));
Assert.assertNull(component.findAncestor(TestButton.class));

}

Expand Down

0 comments on commit e084d39

Please sign in to comment.