cdc.io.data.Child Maven / Gradle / Ivy
package cdc.io.data;
import cdc.util.lang.CollectionUtils;
/**
* Interface implemented by child nodes: they have an optional parent.
*
* This may be:
*
* - Element
*
- Text
*
- Comment
*
*
* @author Damien Carbonne
*
*/
public interface Child extends Node {
@Override
Child clone(boolean recurse);
/**
* Returns the highest ancestor of this child that is a child.
*
* This may be this child.
*
* @return The root child of this child.
*/
public default Child getRootChild() {
Child index = this;
while (index.getParent() instanceof Child) {
index = (AbstractChild) index.getParent();
}
return index;
}
/**
* @return The parent of this child. It may be {@code null}.
*/
public Parent getParent();
/**
* Returns the parent of this child, cast to a target class.
*
* @param The target type.
* @param parentClass The target class.
* @return The parent of this child as a {@code parentClass} object.
*/
public default E getParent(Class parentClass) {
return parentClass.cast(getParent());
}
/**
* Sets or changes the parent of this child.
*
* @param parent The new parent. May be {@code null}.
* @return This object.
* @throws IllegalStateException When {@code parent} can not not be set.
*/
public Child setParent(Parent parent);
/**
* @return The index of this child or -1.
*/
public default int getIndex() {
if (getParent() != null) {
return getParent().getChildren().indexOf(this);
} else {
return -1;
}
}
/**
* Set the index of this child.
*
* @param to The new index of this child.
* @return This object.
* @throws IllegalArgumentException When this child has no parent,
* or {@code to < 0 or to >= getParent().getChildrenCount()}.
*/
public default Child setIndex(int to) {
CollectionUtils.setIndex(getParent().getChildren(), this, to);
return this;
}
/**
* Detach this child from its parent.
*
* Equivalent to {@code setParent(null)}.
*
* @return This object.
*/
public default Child detach() {
return setParent(null);
}
}